LINQ Order By query

Introduction


In order to sort a list of entities in an ascending order with LINQ, we use the OrderBy method.

OrderBy


The OrderBy method allows you to sort a list of elements in an ascending order.

Examples


Simple usage

List<int> list = new List<int> { 8000, 12, 900, 4, 1, 200};

List<int> values = list.OrderBy(l => l).ToList(); // {1, 4, 12, 200, 900, 8000}

Note: we use the ToList method in order to avoid the following casting error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.List<int>'. An explicit conversion exists (are you missing a cast?)

Advanced usage

Besides using primitive types with the OrderBy method, we can also use reference types.

public class Person {

    public string FullName { get; set; }

    public int Age { get; set; }
}
List<Person> people = new List<Person> {
    new Person { FullName = "Marc Thompson", Age = 40},
    new Person { FullName = "Helen Walsh", Age = 53},
    new Person { FullName = "Kelvin Terry", Age = 23},
    new Person { FullName = "Carolyn Poole", Age = 17}
}; 

List<Person> values = people.OrderBy(l => l.Age).ToList(); // sorting people based on their age in an ascending order

    /*
    Result:
    Carolyn Poole, 17
    Kelvin Terry, 23
    Marc Thompson, 40
    Helen Walsh, 53
    */

Namespace


To use the OrderBy method, you have to include this namespace:

using System.Linq;

See also