C# LINQ Introduction
breigo
33.4K views
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);
}
// {
}
}
// }
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.
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds