LINQ OrderBy

Summary: in this tutorial, you’ll learn how to use LINQ OrderBy() method to sort the elements of a sequence in ascending order.

Introduction to the LINQ OrderBy method

The OrderBy() method sorts the elements of a sequence in ascending order:

IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector
);Code language: C# (cs)

In this syntax:

  • TSource is the type of elements in the source sequence.
  • TKey is the type of key returned by keySelector.
  • The source represents an input sequence to sort, which has the type of IEnumrable<TSource>.
  • The keySelector is a function to extract a key from an element.

The OrderBy() method returns an IOrderedEnumerable<TSource> that contains the sorted elements specified by a key.

The OrderBy() method throws an ArgumentNullException if the source or keySelector is null.

LINQ OrderBy examples

Let’s take some examples of using the LINQ OrderBy() method.

1) Using the LINQ OrderBy() method to sort a sequence of numbers

The following program demonstrates how to use the OrderBy() method to sort a sequence of numbers:

using static System.Console;

var scores = new List<int> { 1, 5, 2, 3, 8, 7 ,9 };
var sortedScores = scores.OrderBy(n => n);

foreach (var score in sortedScores)
{
    Write($"{score} ");
}Code language: C# (cs)

Output:

1 2 3 5 7 8 9Code language: C# (cs)

How it works.

First, define a list of integers called scores and initialize it with a sequence of unordered integers:

var scores = new List<int> { 1, 5, 2, 3, 8, 7 ,9 };Code language: C# (cs)

Second, sort the scores sequence using the OrderBy() method. The OrderBy() method returns a sortedScores with the IEnumerable<int> type, containing elements of the scores sequence but in ascending order:

var sortedScores = scores.OrderBy(n => n);Code language: C# (cs)

The lambda expression n => n specifies the key used for sorting. In this case, it is the integer value itself.

Third, write all elements of the sortedScores into the console using a foreach loop and Write() method:

foreach (var score in sortedScores)
{
    Write($"{score} ");
}Code language: C# (cs)

2) Using the LINQ OrderBy() method to sort a sequence of strings

The following program demonstrates how to use the OrderBy() method to sort a sequence of strings:

using static System.Console;

var names = new List<string> { "Olivia","Ava", "Ethan", "Sophia", "Lucas" };

var sortedNames = names.OrderBy(name=>name);

foreach (var name in sortedNames)
{
    Write($"{name} ");
}Code language: C# (cs)

Output:

Ava Ethan Lucas Olivia SophiaCode language: C# (cs)

How it works.

First, create a List<string> that contains 5 names:

var names = new List<string> { "Olivia","Ava", "Ethan", "Sophia", "Lucas" };Code language: C# (cs)

Second, sort the names list using the OrderBy clause. The lambda expression name => name specifies the key to order, which is the string value itself in this case:

var sortedNames = names.OrderBy(name=>name);Code language: C# (cs)

Third, write each name in the sortedNames list to the console:

foreach (var name in sortedNames)
{
    Write($"{name} ");
}Code language: C# (cs)

3) Using the LINQ OrderBy() method to sort a sequence of objects by its properties

The following program demonstrates how to use the OrderBy() method to sort a list of Employee objects by names alphabetically:

using static System.Console;

class Employee
{
    public string? Name { get; set; }
    public string? Department { get; set; }
    public int Salary { get; set; }
}
class Program
{
    public static void Main()
    {
        var employees = new List<Employee>() 
        {
                new Employee { Name = "John", Department = "HR", Salary = 50000 },
                new Employee { Name = "Jane", Department = "IT", Salary = 60000 },
                new Employee { Name = "Bob", Department = "HR", Salary = 45000 },
                new Employee { Name = "Sara", Department = "IT", Salary = 55000 },
                new Employee { Name = "Tom", Department = "IT", Salary = 65000 }
            };

        var results = employees.OrderBy(e => e.Name);

        foreach (var employee in results)
        {
            WriteLine($"{employee.Name} - {employee.Salary:C}");
        }
    }
}
Code language: C# (cs)

Output:

Bob - $45,000.00
Jane - $60,000.00
John - $50,000.00
Sara - $55,000.00
Tom - $65,000.00Code language: C# (cs)

How it works.

First, define the Employee class that has three properties: Name, Department, and Salary.

class Employee
{
    public string? Name { get; set; }
    public string? Department { get; set; }
    public int Salary { get; set; }
}Code language: C# (cs)

Second, create a new List<Employee> and initialize it with some Employee objects:

var employees = new List<Employee>() 
{
    new Employee { Name = "John", Department = "HR", Salary = 50000 },
    new Employee { Name = "Jane", Department = "IT", Salary = 60000 },
    new Employee { Name = "Bob", Department = "HR", Salary = 45000 },
    new Employee { Name = "Sara", Department = "IT", Salary = 55000 },
    new Employee { Name = "Tom", Department = "IT", Salary = 65000 }
};Code language: PHP (php)

Third, sort the Employee objects by their names using the OrderBy() method. The lambda expression e => e.Name specifies the sort key (Name) for ordering.

var results = employees.OrderBy(e => e.Name);Code language: C# (cs)

Third, write the sorted list of Employee object to the console:

foreach (var employee in results)
{
    WriteLine($"{employee.Name} - {employee.Salary:C}");

}Code language: C# (cs)

Similarly, the following example demonstrates how to sort the employees list by salary in ascending order:

using static System.Console;

class Employee
{
    public string? Name { get; set; }
    public string? Department { get; set; }
    public int Salary { get; set; }
}

class Program
{
    public static void Main()
    {
        var employees = new List<Employee>() 
        {
                new Employee { Name = "John", Department = "HR", Salary = 50000 },
                new Employee { Name = "Jane", Department = "IT", Salary = 60000 },
                new Employee { Name = "Bob", Department = "HR", Salary = 45000 },
                new Employee { Name = "Sara", Department = "IT", Salary = 55000 },
                new Employee { Name = "Tom", Department = "IT", Salary = 65000 }
            };

        var results = employees.OrderBy(e => e.Salary);

        foreach (var employee in results)
        {
            WriteLine($"{employee.Name} - {employee.Salary:C}");
        }
    }
}
Code language: C# (cs)

Output:

Bob - $45,000.00
John - $50,000.00
Sara - $55,000.00
Jane - $60,000.00
Tom - $65,000.00Code language: C# (cs)

Summary

  • Use the LINQ OrderBy() method to sort a sequence of objects by a key in ascending order.
Was this tutorial helpful ?