Skip to content

LINQ Basics

The Course
•
30 min study

You wrote Map and CountWhere yourself in the last lesson. LINQ (Language Integrated Query) is the standard library's collection of such methods, available on every IEnumerable<T>. Learning it replaces many small loops with a line that says what you want.

Where and Select

Where keeps the items that pass a test, and Select turns each item into something else. Chain them, and read the chain from top to bottom. The record here is named Task2 only so it can't clash with the library's System.Threading.Tasks.Task.

A first query C#
var tasks = new List<Task2>
{
    new("Write", 30, false),
    new("Read", 15, true),
    new("Plan", 45, false),
};

var titles = tasks
    .Where(task => !task.Done)
    .Select(task => task.Title.ToUpper());

foreach (string title in titles)
{
    Console.WriteLine(title);
}

record Task2(string Title, int Minutes, bool Done);
Check your prediction
Text
WRITE
PLAN

Sorting

OrderBy sorts by a key, OrderByDescending reverses it, and ThenBy breaks ties. The sort is stable, so items with equal keys keep their relative order. It returns a new sequence; the source doesn't change.

Sort by two keys C#
var people = new[] { ("Cy", 30), ("Ana", 25), ("Ben", 30) };

var sorted = people.OrderByDescending(p => p.Item2).ThenBy(p => p.Item1);

foreach (var person in sorted)
{
    Console.WriteLine(person);
}
Console.WriteLine(people[0]);
Check your prediction
Text
(Ben, 30)
(Cy, 30)
(Ana, 25)
(Cy, 30)

("Cy", 30) is a tuple, a quick way to hold values together. Prefer a record once a value goes beyond a line or two.

Summing up

Some methods reduce a sequence to one value: Count, Sum, Min, Max, Average. Any and All answer yes or no, stopping as soon as they know. They accept a test directly, so you don't need a Where first.

Single answers C#
int[] minutes = { 30, 15, 45 };

Console.WriteLine(minutes.Sum());
Console.WriteLine(minutes.Max());
Console.WriteLine(minutes.Average());
Console.WriteLine(minutes.Count(m => m > 20));
Console.WriteLine(minutes.Any(m => m > 40));
Console.WriteLine(minutes.All(m => m > 20));
Check your prediction
Text
90
45
30
2
True
False

Picking one item

First returns the first match and throws if there isn't one. FirstOrDefault gives default instead: null for a reference type, 0 for an int. Watch for that second case, since 0 could be a real value. Single insists there's exactly one, which makes a useful statement about your data.

First, FirstOrDefault, Single C#
int[] numbers = { 3, 8, 12 };

Console.WriteLine(numbers.First(n => n > 5));
Console.WriteLine(numbers.FirstOrDefault(n => n > 100));
Console.WriteLine(numbers.FirstOrDefault(n => n > 100, -1));
Console.WriteLine(numbers.Single(n => n % 3 == 0 && n % 4 == 0));
Console.WriteLine(numbers.Take(2).Last());
Console.WriteLine(numbers.Skip(2).Count());
Check your prediction
Text
8
0
-1
12
8
1

Fix it: First, when there may be none

This looks up the first score over 100. Run it.

First, when there may be none C#
var scores = new List<int> { 40, 95, 70 };
int best = scores.First(score => score > 100);
Console.WriteLine(best);
Check your prediction
Text
InvalidOperationException
Sequence contains no matching element

First promises an answer, so when nothing matches it can only throw. When "no match" is a normal possibility, the code should say what to do instead. Fix it to print none over 100.

Fix it

Use FirstOrDefault with a fallback, and handle the fallback:

C#
var scores = new List<int> { 40, 95, 70 };
int best = scores.FirstOrDefault(score => score > 100, -1);
Console.WriteLine(best == -1 ? "none over 100" : best.ToString());
Text
none over 100

Without the second argument, FirstOrDefault returns 0 for an int, which looks like a real score. Choose a fallback that can't be mistaken for data, or use Any first. Keep First for when an empty result really is a bug, because then the exception is what you want.

Your turn

Exercise

Query a scoreboard

Using a record Score(string Player, int Points, bool Ranked) and the data in the workspace, write one query for each:

  1. Names of ranked players with at least 50 points, highest points first, with ties in name order. Print them joined with commas.
  2. The total points of ranked players.
  3. Whether any unranked player has over 90 points.
  4. The name of the first player with fewer than 10 points, or nobody.

When it works, it prints:

Text
Ana,Di,Ben
230
True
nobody
Your workspace C#
var scores = new List<Score>
{
    new("Ana", 80, true),
    new("Ben", 50, true),
    new("Cy", 95, false),
    new("Di", 80, true),
    new("Ed", 20, true),
};

Console.WriteLine(scores.Count);

record Score(string Player, int Points, bool Ranked);
Hint 1: the idea

Each answer is a short chain. Filter first, then sort, then choose what to keep. Remember that FirstOrDefault can take a fallback value.

Hint 2: a first step

Start with scores.Where(...) for the first query and print its count before adding OrderByDescending, ThenBy and Select.

Show one solution
C#
var scores = new List<Score>
{
    new("Ana", 80, true),
    new("Ben", 50, true),
    new("Cy", 95, false),
    new("Di", 80, true),
    new("Ed", 20, true),
};

var names = scores
    .Where(score => score.Ranked && score.Points >= 50)
    .OrderByDescending(score => score.Points)
    .ThenBy(score => score.Player)
    .Select(score => score.Player);
Console.WriteLine(string.Join(",", names));

Console.WriteLine(scores.Where(score => score.Ranked).Sum(score => score.Points));
Console.WriteLine(scores.Any(score => !score.Ranked && score.Points > 90));

string low = scores.FirstOrDefault(score => score.Points < 10)?.Player ?? "nobody";
Console.WriteLine(low);

record Score(string Player, int Points, bool Ranked);
Text
Ana,Di,Ben
230
True
nobody

The filter comes first, so the sort only handles the rows that matter, and Select comes last, because sorting needs the points that it throws away. ThenBy breaks the tie between Ana and Di without undoing the sort by points, which a second OrderBy would do. FirstOrDefault(…)?.Player ?? "nobody" turns "no such score" into a value in one expression, with no exception and no null left over.

Was this article helpful?

Your response is saved on this device.