LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
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
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.