Skip to content
C#

LINQ Query

Filter, project, sort, group, and aggregate sequences with LINQ.

By EZ4Code Team
linqquery

Code

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

var people = new List<Person> {
    new("Alice", 30),
    new("Bob", 17),
    new("Carol", 25),
    new("Dave", 16),
};

// Query syntax
var adults = from p in people
             where p.Age >= 18
             orderby p.Age descending
             select p;

// Method syntax
var names = people
    .Where(p => p.Age >= 18)
    .OrderByDescending(p => p.Age)
    .Select(p => p.Name)
    .ToList();

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

// Aggregation
var avg = people.Average(p => p.Age);
var oldest = people.MaxBy(p => p.Age);
Console.WriteLine($"avg={avg:F1} oldest={oldest.Name}");

// Grouping
var byAdult = people.GroupBy(p => p.Age >= 18);
foreach (var g in byAdult)
    Console.WriteLine($"{g.Key}: {g.Count()}");

record Person(string Name, int Age);

Explanation

LINQ provides a uniform query syntax over any IEnumerable, with method-syntax equivalents for every operator. Where filters, OrderBy sorts, Select projects, and GroupBy partitions elements into buckets keyed by a function. Aggregations like Average and MaxBy summarize sequences in one pass without manual loops.

More C# Snippets