LINQ Examples in C#: Filter, Group, Sort and Project

LINQ (Language Integrated Query) lets you filter, sort, group and transform any collection with a few chained method calls instead of hand-written loops. It works on arrays, lists and anything else that implements IEnumerable<T>, and the same operators translate to SQL when you use Entity Framework Core.

The examples below run as a .NET console app with top-level statements; System.Linq is included by the default implicit usings. Each shows the method syntax most C# code uses, and the query syntax where it reads better.

Filter with Where

int[] numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0];

// Method syntax
var lowNumbers = numbers.Where(n => n < 7);

// Query syntax, compiles to the same calls
var lowNumbers2 =
    from n in numbers
    where n < 7
    select n;

Console.WriteLine(string.Join(", ", lowNumbers));
// 5, 4, 1, 3, 6, 2, 0

Where keeps the original order. Query syntax is translated by the compiler into exactly the same method calls, so pick whichever is clearer; method syntax wins for short queries, query syntax for joins and let clauses.

Sort with OrderBy and ThenBy

string[] words = ["banana", "apple", "strawberry", "cheese", "pineapple", "book", "angel", "section"];

var byLength = words.OrderBy(w => w.Length);
Console.WriteLine(string.Join(", ", byLength));
// book, apple, angel, banana, cheese, section, pineapple, strawberry

var byLengthThenName = words
    .OrderBy(w => w.Length)
    .ThenBy(w => w, StringComparer.Ordinal);
Console.WriteLine(string.Join(", ", byLengthThenName));
// book, angel, apple, banana, cheese, section, pineapple, strawberry

OrderBy is a stable sort: words of equal length keep their original order, which is why apple comes before angel in the first result. Add ThenBy for a secondary key. Calling OrderBy twice does not do that: the second call becomes the primary key and the first one is demoted to a tiebreaker. For descending order use OrderByDescending and ThenByDescending.

Pass a comparer when sorting strings. Without one, LINQ uses the current culture’s rules, which differ between machines. StringComparer.Ordinal sorts by character code and gives the same result everywhere.

Group with GroupBy

var groups = words.GroupBy(w => w[0]);

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");
}
// b: banana, book
// a: apple, angel
// s: strawberry, section
// c: cheese
// p: pineapple

Each group is an IGrouping<TKey, TElement>: a sequence of the items with a Key property on top. Groups appear in the order their first item appears in the source. Add .OrderBy(g => g.Key) if you want them sorted.

If you only need the counts, .NET 9 added CountBy, which skips building the groups:

foreach (var (letter, count) in words.CountBy(w => w[0]))
{
    Console.WriteLine($"{letter}: {count}");
}
// b: 2
// a: 2
// s: 2
// c: 1
// p: 1

Project with Select, and aggregate

Real data is usually objects, not strings. Here a record holds products, and one query groups them, aggregates each group and sorts the result:

Product[] products =
[
    new("Keyboard", "Hardware", 49.90m),
    new("Mouse", "Hardware", 19.90m),
    new("IDE license", "Software", 199.00m),
    new("Monitor", "Hardware", 229.00m),
    new("Backup tool", "Software", 39.00m),
];

var summary = products
    .GroupBy(p => p.Category)
    .Select(g => new
    {
        Category = g.Key,
        Count = g.Count(),
        Total = g.Sum(p => p.Price)
    })
    .OrderByDescending(x => x.Total);

foreach (var row in summary)
{
    Console.WriteLine($"{row.Category}: {row.Count} items, {row.Total:0.00}");
}
// Hardware: 3 items, 298.80
// Software: 2 items, 238.00

record Product(string Name, string Category, decimal Price);

The shown output assumes an English or invariant culture; in German the totals print as 298,80. The record declaration has to come after the top-level statements.

Other operators you will use all the time:

  • Any(predicate) checks whether at least one item matches and stops at the first one. Prefer it over Count() > 0.
  • First throws if nothing matches; FirstOrDefault returns default, which is null for classes and 0 for int. Since .NET 6 you can pass your own fallback: numbers.FirstOrDefault(n => n > 100, -1).
  • ToDictionary(p => p.Name) throws on a duplicate key; ToLookup allows several items per key.
  • Distinct, and since .NET 6 DistinctBy(p => p.Category), MinBy and MaxBy.

Deferred execution

A LINQ query does not run when you write it. It runs every time you enumerate it:

var list = new List<int> { 1, 2, 3 };
var bigOnes = list.Where(n => n > 1);

list.Add(4);

Console.WriteLine(bigOnes.Count()); // 3, not 2

That is useful, and it has two consequences to keep in mind. First, enumerating the same query twice does all the work twice; for a query over a database or a slow computation, call ToList() or ToArray() once and reuse the result. Second, modifying a List<T> while a query over it is being enumerated throws an InvalidOperationException, so materialize the query before a loop that changes the source.

Methods that return a single value (Count, Sum, First, Any, ToList) run immediately. Methods that return a sequence (Where, Select, OrderBy, GroupBy) are deferred.

The complete list of operators is on Microsoft Learn: Standard query operators overview.

Related examples

Leave a Comment