TExcelTAD
Home › C# › C# LINQ

C# LINQ

LINQ (Language Integrated Query) is a set of methods for querying and transforming data: filter it, sort it, group it, project it into new shapes, combine it. It works on arrays, lists, dictionaries and any other IEnumerable<T>, and the same ideas apply to databases (via Entity Framework) and XML. Add using System.Linq; to use it.

Your first query

LINQ methods are chained one after another. Each takes a lambda — a small inline function like n => n % 2 == 0 — that says what to do with each element.

csharp · try it yourself
using System;
using System.Linq;

int[] numbers = { 5, 12, 8, 3, 17, 20, 6 };

var evensSquared = numbers
    .Where(n => n % 2 == 0)     // keep even numbers
    .OrderBy(n => n)            // sort ascending
    .Select(n => n * n);        // transform each one

Console.WriteLine(string.Join(", ", evensSquared));
Console.WriteLine(
quot;Sum: {numbers.Sum()}, Max: {numbers.Max()}, Average: {numbers.Average():F2}"); Console.WriteLine(
quot;Any > 15? {numbers.Any(n => n > 15)}; all positive? {numbers.All(n => n > 0)}"); Console.WriteLine(
quot;Count over 7: {numbers.Count(n => n > 7)}");
36, 64, 144, 400
Sum: 71, Max: 20, Average: 10.14
Any > 15? True; all positive? True
Count over 7: 4

Common operators

Category Methods
Filtering Where, OfType<T>, Distinct, DistinctBy
Projection Select, SelectMany
Ordering OrderBy, OrderByDescending, ThenBy, Reverse
Element First, FirstOrDefault, Single, Last, ElementAt
Aggregation Count, Sum, Min, Max, Average, Aggregate, MaxBy, MinBy
Quantifiers Any, All, Contains
Partitioning Take, Skip, TakeWhile, Chunk
Grouping & joining GroupBy, Join, Zip, ToLookup
Conversion ToList, ToArray, ToDictionary, ToHashSet

Querying objects

LINQ really shines with collections of objects:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var products = new List<Product>
{
    new("Laptop", "Electronics", 1200m, 5),
    new("Mouse", "Electronics", 25m, 120),
    new("Desk", "Furniture", 300m, 12),
    new("Chair", "Furniture", 150m, 0),
    new("Monitor", "Electronics", 280m, 18),
    new("Lamp", "Furniture", 40m, 33),
};

var inStockByPrice = products
    .Where(p => p.Stock > 0)
    .OrderByDescending(p => p.Price)
    .Select(p => 
quot;{p.Name} ({p.Price})"); Console.WriteLine(string.Join(", ", inStockByPrice)); Product cheapest = products.MinBy(p => p.Price); Console.WriteLine(
quot;Cheapest: {cheapest.Name}"); Product firstFurniture = products.First(p => p.Category == "Furniture"); Console.WriteLine(
quot;First furniture: {firstFurniture.Name}"); Product phone = products.FirstOrDefault(p => p.Name == "Phone"); Console.WriteLine(phone == null ? "No phone found" : phone.Name); decimal stockValue = products.Sum(p => p.Price * p.Stock); Console.WriteLine(
quot;Stock value: {stockValue:N0}"); record Product(string Name, string Category, decimal Price, int Stock);
Laptop (1200), Desk (300), Monitor (280), Lamp (40), Mouse (25)
Cheapest: Mouse
First furniture: Desk
No phone found
Stock value: 18,960

The chair is missing from the first line because its stock is 0 — Where filtered it out before sorting. First throws if nothing matches; FirstOrDefault returns null (or the type's default) instead.

Grouping

GroupBy splits a sequence into groups that share a key. Each group has a Key and is itself a sequence:

csharp · try it yourself
using System;
using System.Linq;

string[] words = { "apple", "avocado", "banana", "blueberry", "cherry", "apricot", "beet" };

var byLetter = words
    .GroupBy(w => w[0])
    .OrderBy(g => g.Key);

foreach (var group in byLetter)
    Console.WriteLine(
quot;{group.Key}: {string.Join(", ", group.OrderBy(w => w))} ({group.Count()})"); var lengths = words.ToDictionary(w => w, w => w.Length); Console.WriteLine(
quot;blueberry has {lengths["blueberry"]} letters"); var longest = words.MaxBy(w => w.Length); Console.WriteLine(
quot;Longest: {longest}");
a: apple, apricot, avocado (3)
b: banana, beet, blueberry (3)
c: cherry (1)
blueberry has 9 letters
Longest: blueberry

Query syntax

LINQ also offers a SQL-like query syntax. The compiler translates it into the same method calls, so use whichever reads better. Method syntax is more common and covers more operators.

csharp · try it yourself
using System;
using System.Linq;

int[] scores = { 88, 42, 95, 67, 73, 59, 100 };

var passed =
    from s in scores
    where s >= 60
    orderby s descending
    select 
quot;{s}%"; Console.WriteLine(string.Join(" ", passed)); // Equivalent method syntax: var same = scores.Where(s => s >= 60).OrderByDescending(s => s).Select(s =>
quot;{s}%"); Console.WriteLine(passed.SequenceEqual(same));
100% 95% 88% 73% 67%
True

Deferred execution

Most LINQ queries are lazy: building the query does no work; it runs each time you enumerate it (with foreach, ToList(), Count(), …). If the source changes in between, the results change too.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var data = new List<int> { 1, 2, 3 };
var big = data.Where(n => n > 1);      // not executed yet
var snapshot = big.ToList();           // executed now

data.Add(10);
Console.WriteLine(string.Join(",", big));       // re-runs the query
Console.WriteLine(string.Join(",", snapshot));  // fixed copy
2,3,10
2,3

Tip: Call ToList() or ToArray() when you want to evaluate a query once and reuse the result, especially if the query is expensive.

Test yourself

Which LINQ method transforms each element into something new?

  1. Where
  2. Select
  3. OrderBy
  4. Any

What does FirstOrDefault return when no element matches (for a class type)?

  1. Throws an exception
  2. null
  3. The first element
  4. An empty object

What is 'deferred execution' in LINQ?

  1. Queries run on a background thread
  2. Queries run only when their results are enumerated
  3. Queries are cached forever
  4. Queries run at compile time