13. LINQ
LINQ (Language Integrated Query) lets you filter, transform, group and summarise any collection with readable method calls, using the same operators for arrays, lists, dictionaries, XML and database queries (Entity Framework). It needs using System.Linq (implicit in new projects). There are two syntaxes: method syntax (nums.Where(n => n > 2).Select(n => n * 10)), which is the most common, and query syntax (from n in nums where n > 2 select n * 10), which reads like SQL. Both compile to the same thing.
Main operators. Filtering: Where, OfType, Distinct, Take, Skip, TakeWhile. Projection: Select, SelectMany. Sorting: OrderBy, OrderByDescending, ThenBy, Reverse. Grouping and joining: GroupBy, Join, Zip. Quantifiers: Any, All, Contains. Element: First, FirstOrDefault, Single, Last, ElementAt, MinBy, MaxBy. Aggregates: Count, Sum, Average, Min, Max, Aggregate. Sets: Union, Intersect, Except, Concat. Conversion: ToList, ToArray, ToDictionary, ToHashSet.
Most LINQ queries are lazy (deferred): they do not run when written, they run each time you enumerate the result (foreach, ToList, Count, Sum...). That means the query sees later changes to the source, and calling ToList() takes a snapshot. Anonymous types (new { Name, Passed }) let Select shape results without declaring a class.
Key points to remember
- LINQ never changes the original collection; it produces a new sequence.
- First() throws if nothing matches, FirstOrDefault() returns null (or 0). Single() throws unless exactly one item matches. Use Any() instead of Count() > 0 to check for items.
- Calling a lazy query several times runs it several times. Use ToList() when you need the results more than once.
- OrderBy sorts ascending and is stable (equal items keep their order); add ThenBy for a second key.
- Select transforms each item; SelectMany flattens a collection of collections into one.
- Aggregate operators on an empty sequence: Sum returns 0, but Min, Max, Average and First throw (use DefaultIfEmpty or check Any first).
- In Entity Framework the same operators are translated to SQL, so the filter runs in the database. Call ToListAsync after Where, not before.
- Do not modify a collection inside a LINQ query that is walking it.
- Prefer readable multi-line chains: one operator per line.
Example 1: Filter, transform, sort
int[] nums = { 5, 2, 8, 1, 9 };
var result = nums.Where(n => n > 2)
.OrderBy(n => n)
.Select(n => n * 10)
.ToList();
Console.WriteLine(string.Join(",", result));
Console.WriteLine(nums.Sum());
Console.WriteLine(nums.Any(n => n > 8));
Show output
Output50,80,90 25 True
Example 2: Query syntax
int[] nums = { 5, 2, 8, 1, 9 };
var query = from n in nums
where n > 2
orderby n descending
select n * 10;
Console.WriteLine(string.Join(",", query));
Show output
Output90,80,50
Example 3: Aggregates
int[] n = { 4, 8, 15, 16, 23, 42 };
Console.WriteLine(n.Count());
Console.WriteLine(n.Sum());
Console.WriteLine(n.Average());
Console.WriteLine(n.Min() + " " + n.Max());
Console.WriteLine(n.Count(x => x % 2 == 0));
Console.WriteLine(n.Take(3).Aggregate((a, b) => a * b)); // 4 * 8 * 15
Show output
Output6 108 18 4 42 4 480
Example 4: Element operators and quantifiers
var names = new List<string> { "Ann", "Ben", "Cleo", "Dan" };
Console.WriteLine(names.First());
Console.WriteLine(names.Last());
Console.WriteLine(names.ElementAt(2));
Console.WriteLine(names.FirstOrDefault(x => x.StartsWith("Z")) ?? "none");
Console.WriteLine(names.Single(x => x.Length == 4));
Console.WriteLine(names.Any(x => x.Length > 3));
Console.WriteLine(names.All(x => x.Length >= 3));
Console.WriteLine(names.Contains("Ben"));
Show output
OutputAnn Dan Cleo none Cleo True True True
Example 5: Paging, Distinct and Range
var items = Enumerable.Range(1, 10); // 1 to 10
Console.WriteLine(string.Join(",", items.Skip(3).Take(3))); // page 2, size 3
Console.WriteLine(string.Join(",", new[] { 1, 2, 2, 3, 3, 3 }.Distinct()));
Console.WriteLine(string.Join(",", items.Where(n => n % 2 == 1).Select(n => n * n)));
Console.WriteLine(string.Join(",", items.TakeWhile(n => n < 4)));
Console.WriteLine(string.Join(",", items.Reverse().Take(2)));
Show output
Output4,5,6 1,2,3 1,9,25,49,81 1,2,3 10,9
Example 6: Working with objects
var students = new List<Student>
{
new("Ann", "Math", 80), new("Ben", "Math", 65), new("Cleo", "Art", 92),
new("Dan", "Art", 70), new("Eve", "Math", 95)
};
var top = students.Where(s => s.Mark >= 75)
.OrderByDescending(s => s.Mark)
.Select(s => s.Name);
Console.WriteLine(string.Join(", ", top));
Console.WriteLine(students.Average(s => s.Mark));
Console.WriteLine(students.MaxBy(s => s.Mark)!.Name);
var sorted = students.OrderBy(s => s.Course).ThenByDescending(s => s.Mark)
.Select(s => $"{s.Course}-{s.Name}");
Console.WriteLine(string.Join(", ", sorted));
record Student(string Name, string Course, int Mark);
Show output
OutputEve, Cleo, Ann 80.4 Eve Art-Cleo, Art-Dan, Math-Eve, Math-Ann, Math-Ben
Example 7: GroupBy
var students = new List<Student>
{
new("Ann", "Math", 80), new("Ben", "Math", 65), new("Cleo", "Art", 92),
new("Dan", "Art", 70), new("Eve", "Math", 95)
};
foreach (var g in students.GroupBy(s => s.Course))
Console.WriteLine($"{g.Key}: {g.Count()} students, average {g.Average(s => s.Mark)}");
var passRate = students.GroupBy(s => s.Mark >= 70)
.ToDictionary(g => g.Key, g => g.Count());
Console.WriteLine($"Passed {passRate[true]}, failed {passRate[false]}");
record Student(string Name, string Course, int Mark);
Show output
OutputMath: 3 students, average 80 Art: 2 students, average 81 Passed 4, failed 1
Example 8: Select into new shapes, ToDictionary
var students = new List<Student> { new("Ann", 80), new("Ben", 65), new("Cleo", 92) };
var summary = students.Select(s => new { s.Name, Passed = s.Mark >= 70 }).ToList();
foreach (var x in summary)
Console.WriteLine($"{x.Name}: {x.Passed}");
var marks = students.ToDictionary(s => s.Name, s => s.Mark);
Console.WriteLine(marks["Cleo"]);
string[] names = students.Select(s => s.Name).ToArray();
Console.WriteLine(names.Length);
record Student(string Name, int Mark);
Show output
OutputAnn: True Ben: False Cleo: True 92 3
Example 9: SelectMany, set operations and Zip
var teams = new[] { new[] { "a", "b" }, new[] { "c" } };
Console.WriteLine(string.Join(",", teams.SelectMany(t => t))); // flatten
int[] x = { 1, 2, 3, 4 };
int[] y = { 3, 4, 5 };
Console.WriteLine(string.Join(",", x.Union(y)));
Console.WriteLine(string.Join(",", x.Intersect(y)));
Console.WriteLine(string.Join(",", x.Except(y)));
Console.WriteLine(string.Join(",", x.Concat(y)));
string[] names = { "Ann", "Ben" };
int[] marks = { 80, 65 };
Console.WriteLine(string.Join(", ", names.Zip(marks, (n, m) => $"{n}={m}")));
Show output
Outputa,b,c 1,2,3,4,5 3,4 1,2 1,2,3,4,3,4,5 Ann=80, Ben=65
Example 10: Join two lists
var depts = new[] { new Dept(1, "IT"), new Dept(2, "HR") };
var emps = new[] { new Emp("Ann", 1), new Emp("Ben", 2), new Emp("Cy", 1) };
var rows = from e in emps
join d in depts on e.DeptId equals d.Id
select $"{e.Name} works in {d.Name}";
foreach (var row in rows) Console.WriteLine(row);
record Dept(int Id, string Name);
record Emp(string Name, int DeptId);
Show output
OutputAnn works in IT Ben works in HR Cy works in IT
Example 11: Deferred execution
var list = new List<int> { 1, 2, 3 };
var query = list.Where(n => n > 1); // nothing runs yet
list.Add(4);
Console.WriteLine(string.Join(",", query)); // runs now, sees 4
var snapshot = list.Where(n => n > 1).ToList(); // runs now, stores results
list.Add(5);
Console.WriteLine(snapshot.Count);
Console.WriteLine(query.Count()); // runs again, sees 5
Show output
Output2,3,4 3 4