Learn/C#/14. LINQ
Lesson 14 of 15
Sign in

C#, lesson 14

LINQ

C#'s signature feature is LINQ, Language-Integrated Query. Instead of writing a loop with counters and temporary lists, you describe what you want ("the names of customers who spent over 100, sorted") and LINQ works out the steps. It works on arrays, lists, dictionaries, sets and anything else that implements IEnumerable<T>, and it lives in the System.Linq namespace.

A pipeline of small steps

LINQ methods are chained. Each one takes a sequence and produces a new sequence (or a single value at the end):

The arguments are lambda expressions: s => s >= 60 is a tiny unnamed function that takes s and returns s >= 60. Most LINQ methods take one.

The operators you will use most

2 exercises to try what you just read.

Exercise 1

Order report

Press Ctrl Enter or Check to test your code.

Exercise 2

Word lab

Press Ctrl Enter or Check to test your code.

KindMethods
FilterWhere, Distinct, Take, Skip
TransformSelect, SelectMany
SortOrderBy, OrderByDescending, ThenBy, ThenByDescending
GroupGroupBy, ToDictionary, ToLookup
AggregateCount, Sum, Average, Min, Max, MinBy, MaxBy, Aggregate
QuestionsAny, All, Contains
Pick oneFirst, FirstOrDefault, Last, Single
MaterializeToList, ToArray

First throws if the sequence is empty; FirstOrDefault returns the default value (null or 0) instead. Average and Max also throw on an empty sequence, so check with Any() first when the data might be empty.

Grouping

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

new { Region = ..., Total = ... } creates an anonymous type: a quick, read-only object for holding intermediate results without declaring a record.

Deferred execution

A LINQ query does not run when you write it. It runs when you consume it, with foreach, ToList, Count and so on. If you consume the same query twice, it runs twice. When you need the results more than once, call ToList() or ToArray() once and reuse the list.

Query syntax

LINQ also has a SQL-like query syntax. The compiler turns it into the same method calls, so pick whichever reads better:

Most C# code uses the method syntax shown above, and some operators (Count, Max, Take) exist only as methods.

Further reading

  • Language-Integrated Query (LINQ)
  • Standard query operators overview
  • Grouping data
  • Lambda expressions

Each input line is an order: <customer> <amount>, where the amount has up to two decimal places. There is at least one order. The starter reads the orders into a list of Order records. Using LINQ, print:

Orders: <number of orders>
Revenue: <sum of all amounts>
Biggest order: <largest amount>
Big orders: <number of orders of 100 or more>

followed by one line per customer, <customer> <total>, highest total first and ties in ordinal order of the name. All money values use two decimals.

Sample input:

ana 120.00
bo 35.50
ana 15.25
cy 99.99
bo 64.50

Sample output:

Orders: 5
Revenue: 335.24
Biggest order: 120.00
Big orders: 1
ana 135.25
bo 100.00
cy 99.99

Read one line of words separated by spaces (at least one word). Using LINQ, print:

  • Words: the number of words,
  • Unique: the number of different words, ignoring case,
  • Longest: the longest word as written (the first one if several tie),
  • Short words: every different word of 3 letters or fewer, in lower case, sorted in ordinal order and separated by , (or - if there are none).

Sample input:

The quick brown fox jumps over the lazy dog

Sample output:

Words: 9
Unique: 8
Longest: quick
Short words: dog, fox, the
using System.Linq;

int[] scores = [72, 95, 41, 88, 60];

var passed = scores
    .Where(s => s >= 60)          // filter:    72, 95, 88, 60
    .OrderByDescending(s => s)    // sort:      95, 88, 72, 60
    .Select(s => $"{s}%")         // transform: "95%", "88%", ...
    .ToList();                    // run it and store the results

Console.WriteLine(string.Join(" ", passed));   // 95% 88% 72% 60%
string[] words = ["kiwi", "apple", "fig", "banana"];
words.Count(w => w.Length > 3);          // 3
words.Any(w => w.StartsWith('f'));       // True
words.Max(w => w.Length);                // 6
words.MaxBy(w => w.Length);              // "banana"
words.Sum(w => w.Length);                // 18
List<Sale> sales = [new("north", 10m), new("south", 4m), new("north", 6m)];

var totals = sales
    .GroupBy(s => s.Region)
    .Select(g => new { Region = g.Key, Total = g.Sum(s => s.Amount) })
    .OrderByDescending(x => x.Total);

foreach (var t in totals)
{
    Console.WriteLine($"{t.Region}: {t.Total}");   // north: 16, then south: 4
}

record Sale(string Region, decimal Amount);   // types go after top-level statements
var passed = from s in scores
             where s >= 60
             orderby s descending
             select s;