Skip to content
Codewilds

Lesson 30 of 34 · LINQ & Errors

LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate

medium20 XP3 min read

You have written many loops that filter, transform, count and sum collections. LINQ (Language Integrated Query) lets you express those operations as a short chain of clearly named steps. It is one of the features developers love most about C#, and you will find it in almost every .NET codebase.

Lambdas: tiny inline functions

LINQ methods take lambda expressions describing what to do with each element. x => x * 2 reads "given x, produce x * 2"; q => q.Reward > 100 is a condition. You met one already with List.RemoveAll.

Filtering, transforming, sorting

int[] scores = { 72, 95, 58, 88, 95 };

var passed = scores.Where(s => s >= 60);              // 72, 95, 88, 95
var curved = scores.Select(s => s + 5);               // 77, 100, 63, 93, 100
var sorted = scores.OrderByDescending(s => s);        // 95, 95, 88, 72, 58
var labels = scores.Where(s => s >= 90)
                   .Select(s => $"A ({s})")
                   .ToList();                         // ["A (95)", "A (95)"]

LINQ methods work on anything enumerable — arrays, lists, dictionaries, strings — and return a new sequence; the original collection never changes. Use ThenBy for a second sort key, Order() for simple values, Distinct() to drop duplicates and Take(n) / Skip(n) to slice.

Asking questions and aggregating

scores.Count();                  // 5
scores.Count(s => s > 90);       // 2
scores.Sum();                    // 408
scores.Average();                // 81.6
scores.Max();                    // 95
scores.Any(s => s < 60);         // true
scores.All(s => s > 0);          // true
scores.First(s => s > 80);       // 95 — throws if nothing matches
scores.FirstOrDefault(s => s > 99);   // 0 — the default value instead

GroupBy

GroupBy sorts elements into buckets by a key. Each group has a Key and contains its elements, so you can count or sum them:

string[] words = { "ant", "bee", "bear", "cat", "bat" };
var byLetter = words.GroupBy(w => w[0]);
foreach (var group in byLetter)
{
    Console.WriteLine($"{group.Key}: {string.Join(",", group)}");
}
// a: ant
// b: bee,bear,bat
// c: cat

var counts = words.GroupBy(w => w.Length)
                  .ToDictionary(g => g.Key, g => g.Count());   // 3 → 4, 4 → 1

Aggregate

Aggregate folds a sequence into one value, carrying an accumulator from element to element — the general form of Sum:

int product = new[] { 2, 3, 4 }.Aggregate(1, (acc, n) => acc * n);    // 24
string path = new[] { "realm", "citadel", "forge" }
    .Aggregate((acc, part) => acc + "/" + part);                       // realm/citadel/forge

Deferred execution

Most LINQ chains do not run when you write them — they run when you enumerate the result (with foreach, ToList(), Count() …). Call ToList() or ToArray() when you want to capture the results once, especially before changing the source collection.

C# also has a query syntax (from s in scores where s > 60 select s) that compiles to the same method calls; the method syntax shown here is more common.

Common mistakes

  • Forgetting ToList() when a method must return a List<T>.
  • First() on an empty sequence throws InvalidOperationException — use FirstOrDefault() or check Any().
  • Integer averages by hand: Sum() / Count() on ints is integer division; Average() returns a double.

Assignment

Quest(Title, Region, Reward, Completed) is a record. Complete QuestLog using LINQ:

  1. CompletedTitles(quests) returns the titles of completed quests, sorted alphabetically.
  2. TotalReward(quests, region) sums the rewards of all quests in a region.
  3. TopRewards(quests, count) returns the titles of the count best-paying quests, highest first (equal rewards sorted by title).
  4. CountByRegion(quests) returns how many quests each region has.
  5. RichestRegion(quests) returns the region with the highest total reward, or "" when there are no quests.
  6. LongestTitle(quests) returns the longest title (the first one on a tie), or "" when there are no quests.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Transforming collections in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 30 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.