C# Tutorial · Collections and LINQ · Lesson 17 of 22

C# LINQ

Query collections with Where, Select, OrderBy, GroupBy and aggregates.

Language Integrated Query

LINQ adds query methods to every collection. They're lazy, chainable and read like a description of the result:

Example 1
int[] nums = { 5, 2, 8, 1, 9, 4 };
var evensSquared = nums.Where(n => n % 2 == 0).Select(n => n * n).OrderBy(n => n);
Console.WriteLine(string.Join(", ", evensSquared));
Console.WriteLine($"{nums.Sum()} {nums.Average():F2} {nums.Max()} {nums.Count(n => n > 4)}");
Console.WriteLine($"{nums.Any(n => n > 8)} {nums.All(n => n > 0)} {nums.First(n => n > 5)}");
Console.WriteLine(string.Join(",", nums.OrderByDescending(n => n).Take(3)));

Output

4, 16, 64
29 4.83 9 3
True True 8
9,8,5

Run this on your computer — see “Get Started” for setup.

Grouping and aggregation

Example 2
var orders = new[]
{
    new Order("Ada", "books", 30m), new Order("Lin", "games", 60m),
    new Order("Ada", "games", 45m), new Order("Sam", "books", 15m),
};
var byCategory = orders
    .GroupBy(o => o.Category)
    .Select(g => new { Category = g.Key, Total = g.Sum(o => o.Total), Count = g.Count() })
    .OrderByDescending(x => x.Total);
foreach (var row in byCategory)
    Console.WriteLine($"{row.Category}: {row.Total} ({row.Count} orders)");
var customers = orders.Select(o => o.Customer).Distinct().Order();
Console.WriteLine(string.Join(", ", customers));

record Order(string Customer, string Category, decimal Total);

Output

games: 105 (2 orders)
books: 45 (2 orders)
Ada, Lin, Sam

Run this on your computer — see “Get Started” for setup.

The same LINQ queries work against databases through Entity Framework Core, which translates them to SQL.

Test yourself

Which LINQ method filters a sequence?

  1. Select
  2. Where
  3. Filter
  4. OrderBy
Show answer

Answer: Where