CS C#

C#: LINQ & Collections

What you will learn

Language Integrated Query (LINQ) lets you query collections with SQL-like syntax. You'll also learn the most common collection types.

LINQ method syntax

using System.Linq;

int[] numbers = { 1, 2, 3, 4, 5, 6 };

var even = numbers.Where(n => n % 2 == 0);      // 2, 4, 6
var doubled = numbers.Select(n => n * 2);      // 2, 4, 6, 8, 10, 12
var sum = numbers.Sum();                       // 21
var firstBig = numbers.FirstOrDefault(n => n > 4);  // 5
var sorted = numbers.OrderByDescending(n => n); // 6, 5, 4, 3, 2, 1

LINQ methods use lambda expressions (n => ...) — the same arrow syntax as JavaScript arrow functions.

LINQ query syntax (alternative)

var even = from n in numbers
           where n % 2 == 0
           select n;

Method syntax is more common in modern C# code.

Common collection types

Type Description Mutable? Use Case
List<T> Dynamic array Yes Ordered items you add/remove
Dictionary<K,V> Key-value map Yes Fast lookups by key
HashSet<T> Unique values Yes Deduplication
Queue<T> FIFO Yes Processing pipeline
Stack<T> LIFO Yes Undo stack, parsing
IEnumerable<T> Anything iterable varies Minimal interface (read-only)
List<string> fruits = new List<string> { "apple", "banana" };
fruits.Add("cherry");

Dictionary<string, int> scores = new() {
    { "Alice", 95 },
    { "Bob", 82 }
};
Console.WriteLine(scores["Alice"]);  // 95

Common mistakes

  • Forgetting using System.Linq; — LINQ methods won't be available
  • Calling .First() on an empty sequence — use .FirstOrDefault() for safety
  • Modifying a collection while iterating with foreach — use for (int i = list.Count - 1; i >= 0; i--) for removal
  • Using List<T> when IEnumerable<T> is sufficient — accept the broadest type in your method parameters

Quick check below!