Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Sort with OrderBy
A common use case is sorting.
For that LINQ offers
OrderBy(keySelector)
andOrderByDescending(keySelector)
Having the possibility to select a key is very helpful, when we want to order objects. This way, we can easily order our people by age:
var people = new List<Person> {
new Person { Name = "...", Age = 5 },
new Person { Name = "...", Age = 8 },
new Person { Name = "...", Age = 3 },
}
var sortedPeople = people.OrderBy(p => p.Age);
We can also sort the objects by multiple keys, e.g. first by Age
and then by Name
.
After calling OrderBy
we get new LINQ methods to chain:
ThenBy(keySelector)
andThenByDescending(keySelector)
OrderBy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// {
using System;
using System.Collections.Generic;
using System.Linq;
namespace Answer
{
public class SortPeopleWithLinq
{
// }
public IEnumerable<Person> SortByNameAndAge(IEnumerable<Person> people)
{
return people
.OrderBy(p => p.Age)
.ThenByDescending(p => p.Name);
}
// {
}
}
// }
Press desired key combination and then press ENTER.
Note: Calling OrderBy
twice would not lead to the expected result, because the second call to OrderBy
would sort the whole collection again. Instead, calling OrderBy
followed by ThenBy
leads to the expected result, because ThenBy
performs a subsequent ordering.
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content