LINQ ThenBy Operator is used when we want to sort the elements in a collection by using multiple properties in ascending order.
This operator must use after OrderBy or OrderByDescending operator. First OrderBy operator sort the collection based on a single property and then we can use ThenBy operator to sort the collection by second property. We can use multiple ThenBy operator in a collection.
Below is the syntax of ThenBy operator.
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector);
ThenBy is an extension method which takes single element and returns the property or field name.
C# ThenBy Example in Query Syntax
List<Student> students = new List<Student>();
students.Add(new Student { Id = 1, Name = "Ramesh", Rank = 1, Age = 39 });
students.Add(new Student { Id = 2, Name = "Kapil", Rank = 1, Age = 32 });
students.Add(new Student { Id = 3, Name = "Suresh", Rank = 2, Age = 45 });
students.Add(new Student { Id = 4, Name = "Mahesh", Rank = 2, Age = 39 });
var studentsOrderByRank = from student in students
orderby student.Rank, student.Age
select student;
Console.WriteLine("Sorted Students:");
foreach (var student in studentsOrderByRank)
{
Console.WriteLine(student.Name);
}
Result
------
Sorted Students:
Kapil
Ramesh
Mahesh
Suresh
In the above example, we sort the collection based on Rank and Age properties. First collection is sorted based on Rank property and then by Age property. If we want to further sort the collection we can add another property by appending comma and property name.
C# ThenBy Example in Method Syntax
List<Student> students = new List<Student>();
students.Add(new Student { Id = 1, Name = "Ramesh", Rank = 1, Age = 39 });
students.Add(new Student { Id = 2, Name = "Kapil", Rank = 1, Age = 32 });
students.Add(new Student { Id = 3, Name = "Suresh", Rank = 2, Age = 45 });
students.Add(new Student { Id = 4, Name = "Mahesh", Rank = 2, Age = 39 });
var studentsOrderByRank = students.OrderBy(w => w.Rank).ThenBy(w => w.Age);
Console.WriteLine("Sorted Students:");
foreach (var student in studentsOrderByRank)
{
Console.WriteLine(student.Name);
}
Result
------
Sorted Students:
Kapil
Ramesh
Mahesh
Suresh
We use method syntax of OrderBy and ThenBy operators to sort the collection based on first Rank property and then by Age property.