Thuta Learning
AdvancedProgrammingbeginner

LINQ: Querying Collections

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Use Where and Select
  • Use OrderBy and aggregate methods
  • Understand deferred execution

Let's break it down simply

LINQ lets you write strongly typed queries against collections and other data sources. Where filters, and Select reshapes the data. Until you call ToList() on a query, it can remain a deferred execution.

csharp
var scores = new[] { 68, 42, 91, 77, 55 };

var passed = scores
    .Where(score => score >= 60)
    .OrderByDescending(score => score)
    .Select(score => $"Score: {score}")
    .ToList();

passed.ForEach(Console.WriteLine);
Console.WriteLine($"Average: {scores.Average():0.0}");
You should see
Score: 91
Score: 77
Score: 68
Average: 66.6

Try it yourself

Filter the Products collection by category, sort by price from lowest to highest, then select just the name and price.

Language Integrated Query (LINQ)Microsoft Learn

Easy traps

  • Assuming the result of Where modifies the original collection
  • Enumerating a query repeatedly inside a loop

Exercise

Filter the Products collection by category, sort by price from lowest to highest, then select just the name and price.

You'll know it worked when: Score: 91 Score: 77 Score: 68 Average: 66.6

LINQ: Querying Collections | Thuta Learning