C#, lesson 14
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.
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.
2 exercises to try what you just read.
| Kind | Methods |
|---|---|
| Filter | Where, Distinct, Take, Skip |
| Transform | Select, SelectMany |
| Sort | OrderBy, OrderByDescending, ThenBy, ThenByDescending |
| Group | GroupBy, ToDictionary, ToLookup |
| Aggregate | Count, Sum, Average, Min, Max, MinBy, MaxBy, Aggregate |
| Questions | Any, All, Contains |
| Pick one | First, FirstOrDefault, Last, Single |
| Materialize | ToList, 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.
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.
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.
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.
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.50Sample output:
Orders: 5
Revenue: 335.24
Biggest order: 120.00
Big orders: 1
ana 135.25
bo 100.00
cy 99.99Read 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 dogSample output:
Words: 9
Unique: 8
Longest: quick
Short words: dog, fox, theusing 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); // 18List<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 statementsvar passed = from s in scores
where s >= 60
orderby s descending
select s;