How to sort and filter collections in C#?

To achieve sorting and filtering operations on collections, one can utilize LINQ (Language-Integrated Query) for implementation. Below are some common examples of sorting and filtering operations on collections.

  1. Sort the set.
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };

var sortedNumbers = numbers.OrderBy(x => x);

foreach (var number in sortedNumbers)
{
    Console.WriteLine(number);
}
  1. – Filter the set.
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };

var filteredNumbers = numbers.Where(x => x > 5);

foreach (var number in filteredNumbers)
{
    Console.WriteLine(number);
}
  1. Sort and filter the set.
List<int> numbers = new List<int> { 5, 2, 8, 1, 9 };

var sortedFilteredNumbers = numbers.OrderBy(x => x).Where(x => x > 5);

foreach (var number in sortedFilteredNumbers)
{
    Console.WriteLine(number);
}

By using LINQ, you can easily sort and filter collections, making the code more concise and easier to understand.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds