C# 14 cheatsheet

C# 14: Collections and LINQ

10 common C# 14 tasks.

Create collections concisely

Collection expressions build arrays, lists and spans with the same syntax. .. spreads another collection.

int[] a = [1, 2, 3];
List<int> b = [..a, 4, 5];

Use a dictionary

Add and read values by key. TryGetValue avoids an exception for missing keys.

var ages = new Dictionary<string, int> { ["Ada"] = 36 };
if (ages.TryGetValue("Ada", out var age)) Console.WriteLine(age);

Keep unique items

A set rejects duplicates, and Add returns false if the item was already there.

var seen = new HashSet<string>();
bool isNew = seen.Add("Ada");

Filter and transform

LINQ methods work on any sequence. Nothing runs until you enumerate the result.

var names = users.Where(u => u.Age >= 18).Select(u => u.Name).ToList();

Sort by one or more keys

Sort by one key, then break ties with another.

var sorted = users.OrderBy(u => u.LastName).ThenByDescending(u => u.Age);

Group items

Group by a key and compute a value for each group.

var byCountry = users.GroupBy(u => u.Country)
                     .Select(g => new { Country = g.Key, Count = g.Count() });

Find or test elements

FirstOrDefault returns null or default when nothing matches, while First throws.

var admin = users.FirstOrDefault(u => u.IsAdmin);
bool any = users.Any(u => u.Age > 60);

Total, average and extremes

Compute simple aggregates over a sequence.

var total = orders.Sum(o => o.Amount);
var average = orders.Average(o => o.Amount);
var largest = orders.Max(o => o.Amount);

Join two sequences

Match items from two sequences by a key.

var rows = orders.Join(users, o => o.UserId, u => u.Id, (o, u) => new { u.Name, o.Amount });

Generate numbers

Produce a sequence of integers.

var numbers = Enumerable.Range(1, 5).Select(n => n * n);

Was this page helpful?