When working with collections in C#, you often need to arrange data in a particular order. LINQ (Language Integrated Query) makes this easy with its sorting operators. One of the most commonly used operators is OrderBy().
The OrderBy() operator is used to sort the elements of a collection in ascending order based on a specified key or property.
What is the LINQ OrderBy Operator?
OrderBy() is a LINQ extension method available in C#. It sorts the elements of a sequence according to a specified key.
For example, if you have a list of numbers:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 40, 10, 30, 20, 50 };
var result = numbers.OrderBy(n => n);
foreach (int number in result)
{
Console.WriteLine(number);
}
}
}
Output
10
20
30
40
50
Here, n => n specifies the value that LINQ should use for sorting.
OrderBy() with Objects
OrderBy() becomes particularly useful when working with objects.
Consider a simple Student class:
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
We can create a collection of students and sort them according to their age:
var students = new List
{
new Student { Name = "Rahul", Age = 22 },
new Student { Name = "Priya", Age = 19 },
new Student { Name = "Aman", Age = 21 }
};
var result = students.OrderBy(s => s.Age);
foreach (var student in result)
{
Console.WriteLine(student.Name + " - " + student.Age);
}
The students will be displayed from the youngest to the oldest.
OrderByDescending()
If you need to sort data in descending order, LINQ provides the OrderByDescending() method.
var result = students.OrderByDescending(s => s.Age);
This reverses the sorting direction, placing larger values before smaller ones.
Sorting by Multiple Properties
LINQ also allows you to perform secondary sorting with ThenBy() and ThenByDescending().
For example:
var result = students
.OrderBy(s => s.Age)
.ThenBy(s => s.Name);
Here, students are first sorted by age. If two students have the same age, their names are used as the secondary sorting criteria.
Why Use LINQ OrderBy?
The OrderBy() operator is useful because it provides a clean and readable way to sort collections. It can be used with numbers, strings, objects, database queries, and many other data sources supported by LINQ.
Conclusion
The LINQ OrderBy() operator is an important sorting method for C# developers. It allows you to arrange collection elements in ascending order using a simple lambda expression. When combined with OrderByDescending(), ThenBy(), and ThenByDescending(), it provides flexible options for sorting data.
Top comments (0)