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.
- 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);
}
- – 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);
}
- 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.