LINQ OrderBy operator comes first in LINQ Sorting Operators. OrderBy operator sort the sequence (collection) based on particular property in ascending order.
We can use OrderBy operator both in Query Syntax and Method Syntax.
Below is the syntax of OrderBy operator.
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
As shown in the above syntax, this operator take the element and return only the property name on which we want to sort the sequence (collection).
C# Example of OrderBy Operator in Query Syntax
List<Student> students = new List<Student>();
students.Add(new Student { Id = 1, Name = "Ramesh", Rank = 3 });
students.Add(new Student { Id = 2, Name = "Kapil", Rank = 1 });
students.Add(new Student { Id = 3, Name = "Suresh", Rank = 2 });
var studentsOrderByRank = from student in students
orderby student.Rank
select student;
Console.WriteLine("Sorted Students:");
foreach(var student in studentsOrderByRank)
{
Console.WriteLine(student.Name);
}
Result
------
Sorted Students:
Kapil
Suresh
Ramesh
In the above example, we sort the students using OrderBy operator using Rank property of Student collection. We can sort by any data type like int, string, decimal, float, long.
C# Example OrderBy Operator in Method Syntax
var studentsOrderByRank = students.OrderBy(w => w.Rank);
Console.WriteLine("Sorted Students:");
foreach (var student in studentsOrderByRank)
{
Console.WriteLine(student.Name);
}
We use OrderBy extension method of LINQ. This takes only single element and we have to choose a property name on which we want to sort the collection. In the above example, we return Rank property from the extension method. This extension method returns IOrderedEnumerable<Student> collection which is sorted by Rank property.
By using this operator, we can only sort the sequence based on a single property, but if we want to sort the collection based on multiple properties then we have to use ThenBy Operator that we will see in our next tutorial.