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.
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
WRITE
PLANSorting
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.
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
(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.
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
90
45
30
2
True
FalsePicking 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.
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
8
0
-1
12
8
1Fix it: First, when there may be none
This looks up the first score over 100. Run it.
var scores = new List<int> { 40, 95, 70 };
int best = scores.First(score => score > 100);
Console.WriteLine(best);Check your prediction
InvalidOperationException
Sequence contains no matching elementFirst 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:
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());none over 100Without 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
Query a scoreboard
Using a record Score(string Player, int Points, bool Ranked) and the data in the workspace, write one query for each:
- Names of ranked players with at least 50 points, highest points first, with ties in name order. Print them joined with commas.
- The total points of ranked players.
- Whether any unranked player has over 90 points.
- The name of the first player with fewer than 10 points, or
nobody.
When it works, it prints:
Ana,Di,Ben
230
True
nobodyvar 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
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);Ana,Di,Ben
230
True
nobodyThe 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.
Completion is saved in this browser only. It does not measure mastery.