ZetCode

C# LINQ Order

last modified November 6, 2026

In this article we show how to sort data in C# with LINQ queries.

Language-Integrated Query (LINQ) is a domain-specific language for querying data from various data sources, including arrays, lists, XML files, or databases.

We can use LINQ's Order, OrderDescending, OrderBy, and OrderByDescending methods to order data. Secondary sort keys are added with ThenBy and ThenByDescending. The methods do not mutate the original sequence; they return a new sorted sequence. Like most LINQ operators, they use deferred execution: the sorting happens when the result is enumerated.

In addition, we can use the orderby, ascending, and descending clauses with LINQ query expressions.

C# LINQ Order

The Order method, available since .NET 7, sorts the elements of a sequence in ascending order.

Order<T>(IEnumerable<T>)
Order<T>(IEnumerable<T>, IComparer<T>)

The second method accepts an IComparer.

Program.cs
List<string> words = [
    "world", "War", "abbot", "Caesar", "castle", "sky", "den",
    "forest", "ocean", "water", "falcon", "owl", "rain", "Earth"
];

var sorted = words.Order();
Console.WriteLine(string.Join(", ", sorted));

Console.WriteLine("-------------------------");

var sorted2 = words.Order(StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", sorted2));

Console.WriteLine("-------------------------");

Console.WriteLine(string.Join(", ", words));

We have a list of words. We sort the words in ascending order.

var sorted = words.Order();

We sort the words with Order. Strings are compared with the current culture's rules; such comparison puts words in dictionary order, regardless of the case of the letters.

var sorted2 = words.Order(StringComparer.Ordinal);

To the overloaded method we also pass a string comparer. The StringComparer.Ordinal compares the numeric values of the characters; therefore, all capitalized words come before the lowercase ones.

Console.WriteLine(string.Join(", ", words));

The original list is not modified.

$ dotnet run
abbot, Caesar, castle, den, Earth, falcon, forest, ocean, owl, rain, sky, War, water, world
-------------------------
Caesar, Earth, War, abbot, castle, den, falcon, forest, ocean, owl, rain, sky, water, world
-------------------------
world, War, abbot, Caesar, castle, sky, den, forest, ocean, water, falcon, owl, rain, Earth

C# LINQ OrderDescending

The OrderDescending method sorts the elements of a sequence in descending order.

Program.cs
List<int> vals = [0, -2, 1, -3, 4, 3, 2, 5, 7, -1];

var sorted = vals.OrderDescending();
Console.WriteLine(string.Join(", ", sorted));

In the program, we sort the integers in descending order.

$ dotnet run
7, 5, 4, 3, 2, 1, 0, -1, -2, -3

C# LINQ OrderBy

The OrderBy method sorts the elements of a sequence in ascending order according to a key.

OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>)
OrderBy<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>, IComparer<TKey>)

The method accepts a key selector function, which extracts a key from an element.

Program.cs
List<User> users =
[
    new("John", "Doe", 1230),
    new("Lucy", "Novak", 670),
    new("Ben", "Walter", 2050),
    new("Robin", "Brown", 2300),
    new("Amy", "Doe", 1250),
    new("Joe", "Draker", 1190),
    new("Janet", "Doe", 980),
    new("Albert", "Novak", 1930),
];

Console.WriteLine("sort ascending by last name and salary");

var sortedUsers = users.OrderBy(u => u.LastName).ThenBy(u => u.Salary);

foreach (var user in sortedUsers)
{
    Console.WriteLine(user);
}

record User(string FirstName, string LastName, int Salary);

In the example, we sort the users first by their last names, then by their salaries.

var sortedUsers = users.OrderBy(u => u.LastName).ThenBy(u => u.Salary);

We sort the users by their last names and then by their salaries in ascending order. The key selector function in the form of a lambda extracts the LastName property to be the sort key. Note that calling OrderBy twice would not work; the second call would re-sort the whole sequence. Secondary keys must be given with ThenBy.

$ dotnet run
sort ascending by last name and salary
User { FirstName = Robin, LastName = Brown, Salary = 2300 }
User { FirstName = Janet, LastName = Doe, Salary = 980 }
User { FirstName = John, LastName = Doe, Salary = 1230 }
User { FirstName = Amy, LastName = Doe, Salary = 1250 }
User { FirstName = Joe, LastName = Draker, Salary = 1190 }
User { FirstName = Lucy, LastName = Novak, Salary = 670 }
User { FirstName = Albert, LastName = Novak, Salary = 1930 }
User { FirstName = Ben, LastName = Walter, Salary = 2050 }

C# LINQ OrderByDescending

The OrderByDescending method sorts the elements of a sequence in descending order.

Program.cs
List<User> users =
[
    new("John", "Doe", 1230),
    new("Lucy", "Novak", 670),
    new("Ben", "Walter", 2050),
    new("Robin", "Brown", 2300),
    new("Amy", "Doe", 1250),
    new("Joe", "Draker", 1190),
    new("Janet", "Doe", 980),
    new("Albert", "Novak", 1930),
];

Console.WriteLine("sort descending by last name and salary");

var sortedUsers = users.OrderByDescending(u => u.LastName)
    .ThenByDescending(u => u.Salary);

foreach (var user in sortedUsers)
{
    Console.WriteLine(user);
}

Console.WriteLine("sort by last name, then by salary descending");

var mixed = users.OrderBy(u => u.LastName).ThenByDescending(u => u.Salary);

foreach (var user in mixed)
{
    Console.WriteLine(user);
}

record User(string FirstName, string LastName, int Salary);

In the program, we sort the users by last name and then by salary in descending order.

var mixed = users.OrderBy(u => u.LastName).ThenByDescending(u => u.Salary);

The directions of the keys can be mixed. Here the last names are in ascending order and the salaries within each last name in descending order.

$ dotnet run
sort descending by last name and salary
User { FirstName = Ben, LastName = Walter, Salary = 2050 }
User { FirstName = Albert, LastName = Novak, Salary = 1930 }
User { FirstName = Lucy, LastName = Novak, Salary = 670 }
User { FirstName = Joe, LastName = Draker, Salary = 1190 }
User { FirstName = Amy, LastName = Doe, Salary = 1250 }
User { FirstName = John, LastName = Doe, Salary = 1230 }
User { FirstName = Janet, LastName = Doe, Salary = 980 }
User { FirstName = Robin, LastName = Brown, Salary = 2300 }
sort by last name, then by salary descending
User { FirstName = Robin, LastName = Brown, Salary = 2300 }
User { FirstName = Amy, LastName = Doe, Salary = 1250 }
User { FirstName = John, LastName = Doe, Salary = 1230 }
User { FirstName = Janet, LastName = Doe, Salary = 980 }
User { FirstName = Joe, LastName = Draker, Salary = 1190 }
User { FirstName = Albert, LastName = Novak, Salary = 1930 }
User { FirstName = Lucy, LastName = Novak, Salary = 670 }
User { FirstName = Ben, LastName = Walter, Salary = 2050 }

C# LINQ OrderBy with computed keys and comparers

The key does not have to be a property; it can be any value computed from the element.

Program.cs
List<string> words = ["falcon", "Sky", "by", "water", "Atom", "forest", "owl"];

var byLength = words.OrderBy(w => w.Length);
Console.WriteLine(string.Join(", ", byLength));

var byLast = words.OrderBy(w => w[^1]);
Console.WriteLine(string.Join(", ", byLast));

var ignoreCase = words.OrderBy(w => w, StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", ignoreCase));

We sort words by their length, by their last character, and alphabetically ignoring the case.

var byLast = words.OrderBy(w => w[^1]);

The ^1 index refers to the last character of the word.

var ignoreCase = words.OrderBy(w => w, StringComparer.OrdinalIgnoreCase);

The word itself is the key; a comparer is passed as the third argument.

$ dotnet run
by, Sky, owl, Atom, water, falcon, forest
owl, Atom, falcon, water, forest, Sky, by
Atom, by, falcon, forest, owl, Sky, water

C# LINQ ordering with query expressions

The next example uses the LINQ query expressions to sort data.

Program.cs
List<string> words = [
    "world", "War", "abbot", "Caesar", "castle", "sky", "den",
    "forest", "ocean", "water", "falcon", "owl", "rain", "Earth"
];

var sorted = from word in words
             orderby word
             select word;

Console.WriteLine(string.Join(", ", sorted));

var sorted2 = from word in words
              orderby word descending
              select word;

Console.WriteLine(string.Join(", ", sorted2));

var sorted3 = from word in words
              orderby word.Length descending, word
              select word;

Console.WriteLine(string.Join(", ", sorted3));

We sort a list of words with orderby and descending clauses.

var sorted3 = from word in words
              orderby word.Length descending, word
              select word;

Multiple keys are separated with commas. The compiler translates the second key into a ThenBy call. The words are sorted by their length in descending order; words of the same length are sorted alphabetically.

$ dotnet run
abbot, Caesar, castle, den, Earth, falcon, forest, ocean, owl, rain, sky, War, water, world
world, water, War, sky, rain, owl, ocean, forest, falcon, Earth, den, castle, Caesar, abbot
Caesar, castle, falcon, forest, abbot, Earth, ocean, water, world, rain, den, owl, sky, War

C# LINQ OrderBy custom order

Sometimes the order is given by a list of values rather than by the natural order of the keys.

Program.cs
List<Job> jobs =
[
    new("write report", "medium"),
    new("fix server", "high"),
    new("water plants", "low"),
    new("pay invoice", "high"),
    new("read book", "low"),
];

string[] priorities = ["high", "medium", "low"];

var sorted = jobs.OrderBy(j => Array.IndexOf(priorities, j.Priority));

foreach (var job in sorted)
{
    Console.WriteLine($"{job.Priority,-7}{job.Name}");
}

record Job(string Name, string Priority);

We sort jobs by priority. The position of the priority in the priorities array is used as the sort key. A priority that is not in the array would get index -1 and would come first.

$ dotnet run
high   fix server
high   pay invoice
medium write report
low    water plants
low    read book

C# LINQ OrderBy null values

With the default comparer, null values are considered smaller than any other value.

Program.cs
List<Book> books =
[
    new("Dune", 1965),
    new("Unknown manuscript", null),
    new("Neuromancer", 1984),
    new("Old notes", null),
    new("Foundation", 1951),
];

foreach (var b in books.OrderBy(b => b.Year))
{
    Console.WriteLine($"{b.Year?.ToString() ?? "-",-5} {b.Title}");
}

Console.WriteLine("----------------------");

foreach (var b in books.OrderBy(b => b.Year is null).ThenBy(b => b.Year))
{
    Console.WriteLine($"{b.Year?.ToString() ?? "-",-5} {b.Title}");
}

record Book(string Title, int? Year);

We sort books by their publication year, which may be unknown.

foreach (var b in books.OrderBy(b => b.Year is null).ThenBy(b => b.Year))

To place the null values at the end, we first sort by a boolean key; false precedes true.

$ dotnet run
-     Unknown manuscript
-     Old notes
1951  Foundation
1965  Dune
1984  Neuromancer
----------------------
1951  Foundation
1965  Dune
1984  Neuromancer
-     Unknown manuscript
-     Old notes

C# LINQ stable sorting

The LINQ ordering methods perform a stable sort. Elements with equal keys keep their relative order from the source sequence. This is different from List.Sort and Array.Sort, which are not stable.

Program.cs
List<(string Name, int Age)> people =
[
    ("Lucy", 30),
    ("Adam", 25),
    ("Tom", 30),
    ("Betty", 25),
    ("Anna", 30),
];

foreach (var p in people.OrderBy(p => p.Age))
{
    Console.WriteLine(p);
}

The people are sorted by age. Lucy, Tom, and Anna have the same age and they appear in the same order as in the source list.

$ dotnet run
(Adam, 25)
(Betty, 25)
(Lucy, 30)
(Tom, 30)
(Anna, 30)

C# LINQ ordering a dictionary

A dictionary has no defined order, but we can sort its key-value pairs with LINQ.

Program.cs
Dictionary<string, int> scores = new()
{
    ["Paul"] = 78,
    ["Anna"] = 92,
    ["Peter"] = 65,
    ["Lucy"] = 92,
    ["Martin"] = 81,
};

var ranking = scores.OrderByDescending(e => e.Value).ThenBy(e => e.Key);

foreach (var (name, score) in ranking)
{
    Console.WriteLine($"{name}: {score}");
}

var top3 = scores.OrderByDescending(e => e.Value).Take(3).Select(e => e.Key);
Console.WriteLine(string.Join(", ", top3));

We create a ranking of students by their scores. Students with the same score are sorted by name.

var top3 = scores.OrderByDescending(e => e.Value).Take(3).Select(e => e.Key);

Combined with Take, ordering gives us the top elements.

$ dotnet run
Anna: 92
Lucy: 92
Martin: 81
Paul: 78
Peter: 65
Anna, Lucy, Martin

C# LINQ join and order

In the next example, we perform ordering operation on a join operation.

Program.cs
List<Country> countries =
[
    new("Slovakia", 1),
    new("Hungary", 2),
    new("Romania", 3),
    new("Poland", 4)
];

List<City> cities =
[
    new("Bratislava", 1),
    new("Poprad", 1),
    new("Trnava", 1),
    new("Budapest", 2),
    new("Miskolc", 2),
    new("Ajka", 2),
    new("Bucharest", 3),
    new("Cluj-Napoca", 3),
    new("Iasi", 3),
    new("Brasov", 3),
    new("Warsaw", 4),
    new("Krakow", 4),
];

var groups =
    from country in countries
    join city in cities on country.Id equals city.CountryId into cGroup
    orderby country.Name
    select new
    {
        Country = country.Name,
        Cities =
            from city2 in cGroup
            orderby city2.Name
            select city2
    };

foreach (var group in groups)
{
    Console.WriteLine(group.Country);

    foreach (var city in group.Cities)
    {
        Console.WriteLine($"  {city.Name}");
    }
}

record City(string Name, int CountryId);
record Country(string Name, int Id);

We have countries and their corresponding cities. We join the cities with their countries. We output the countries in ascending order and cities inside countries also in ascending order.

var groups =
    from country in countries
    join city in cities on country.Id equals city.CountryId into cGroup
    orderby country.Name
    select new
    {
        Country = country.Name,
        Cities =
            from city2 in cGroup
            orderby city2.Name
            select city2
    };

We join the cities with their countries. The key is the country Id. The into keyword creates a group join; cGroup holds the cities of each country. We order the countries and the cities with orderby.

$ dotnet run
Hungary
  Ajka
  Budapest
  Miskolc
Poland
  Krakow
  Warsaw
Romania
  Brasov
  Bucharest
  Cluj-Napoca
  Iasi
Slovakia
  Bratislava
  Poprad
  Trnava

Source

Enumerable.OrderBy method

In this article we have ordered data in C# with LINQ.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.