ThenBy
How do I order an array or list on multiple properties or fields? This is where ThenBy
can be used.
Basic example
We have a list of people and we need to order by their names alphabetically in ascending order, followed by their age in ascending order.
Method syntax
In the Method syntax, we can simply chain the OrderBy
and ThenyBy
methods.
Live example: https://dotnetfiddle.net/CnQkAx
var people = new[]
{
new {Name = "Jennifer", Age = 21},
new {Name = "Alton", Age = 22},
new {Name = "Adam", Age = 27},
new {Name = "Milford", Age = 23},
new {Name = "James", Age = 23}
};
var orderedPeople = people.OrderBy(x => x.Name)
.ThenBy(x => x.Age);
// output:
// { Name = Adam, Age = 27 }
// { Name = Alton, Age = 22 }
// { Name = James, Age = 23 }
// { Name = Jennifer, Age = 21 }
// { Name = Milford, Age = 23 }
Query syntax
In the query syntax, you simply specify the following property by a separating comma.
Live example: https://dotnetfiddle.net/uqmSAO
var people = new[]
{
new {Name = "Jennifer", Age = 21},
new {Name = "Alton", Age = 22},
new {Name = "Adam", Age = 27},
new {Name = "Milford", Age = 23},
new {Name = "James", Age = 23}
};
var orderedPeople = from person in people
orderby person.Name , person.Age
select person;
// output:
// { Name = Adam, Age = 27 }
// { Name = Alton, Age = 22 }
// { Name = James, Age = 23 }
// { Name = Jennifer, Age = 21 }
// { Name = Milford, Age = 23 }