0
0
CsharpHow-ToBeginner · 4 min read

How to Use LINQ OrderBy in C# for Sorting Collections

Use OrderBy in LINQ to sort a collection by a key in ascending order. It takes a lambda expression to specify the property or value to sort by and returns a new sorted sequence.
📐

Syntax

The OrderBy method sorts elements of a sequence in ascending order based on a key you provide.

  • source.OrderBy(keySelector): source is the collection to sort.
  • keySelector is a function that selects the value to sort by from each element.
  • Returns a new sorted IOrderedEnumerable sequence.
csharp
var sorted = collection.OrderBy(item => item.Property);
💻

Example

This example shows how to sort a list of numbers and a list of objects by a property using OrderBy.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    static void Main()
    {
        // Sort numbers
        List<int> numbers = new List<int> { 5, 3, 8, 1 };
        var sortedNumbers = numbers.OrderBy(n => n);
        Console.WriteLine("Sorted numbers: " + string.Join(", ", sortedNumbers));

        // Sort people by Age
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };
        var sortedPeople = people.OrderBy(p => p.Age);
        Console.WriteLine("People sorted by age:");
        foreach (var person in sortedPeople)
        {
            Console.WriteLine($"{person.Name} - {person.Age}");
        }
    }
}
Output
Sorted numbers: 1, 3, 5, 8 People sorted by age: Bob - 25 Alice - 30 Charlie - 35
⚠️

Common Pitfalls

Common mistakes when using OrderBy include:

  • Not realizing OrderBy returns a new sorted sequence and does not change the original collection.
  • Using OrderBy multiple times without ThenBy can override previous sorting.
  • Sorting by a key that can be null without handling it may cause runtime errors.
csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string> { "apple", "banana", "cherry" };

        // Wrong: calling OrderBy twice resets sorting
        var wrongSort = fruits.OrderBy(f => f.Length).OrderBy(f => f);
        Console.WriteLine("Wrong sort: " + string.Join(", ", wrongSort));

        // Right: use ThenBy to add secondary sorting
        var rightSort = fruits.OrderBy(f => f.Length).ThenBy(f => f);
        Console.WriteLine("Right sort: " + string.Join(", ", rightSort));
    }
}
Output
Wrong sort: apple, banana, cherry Right sort: apple, cherry, banana
📊

Quick Reference

Tips for using OrderBy:

  • Use OrderBy for ascending order sorting.
  • Use OrderByDescending for descending order.
  • Chain ThenBy or ThenByDescending for multi-level sorting.
  • Remember it returns a new sorted sequence; original stays unchanged.

Key Takeaways

Use OrderBy with a key selector lambda to sort collections in ascending order.
OrderBy returns a new sorted sequence and does not modify the original collection.
Chain ThenBy for additional sorting levels after OrderBy.
Be careful calling OrderBy multiple times; use ThenBy to preserve previous sorting.
Handle null keys properly to avoid runtime errors.