C# Course

C# LINQ: Query Collections Like a Pro

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

What is LINQ?

LINQ (Language Integrated Query) lets you query any IEnumerable collection — arrays, lists, databases, XML — using a readable, declarative syntax. It was introduced in C# 3.0.

Basic LINQ with Method Syntax

using System;
using System.Collections.Generic;
using System.Linq;

var numbers = new List<int> { 5, 2, 8, 1, 9, 3, 7, 4, 6 };

// Filter (Where)
var evens = numbers.Where(n => n % 2 == 0).ToList();
// [2, 8, 4, 6]

// Sort (OrderBy)
var sorted = numbers.OrderBy(n => n).ToList();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Transform (Select)
var squares = numbers.Select(n => n * n).ToList();
// [25, 4, 64, 1, 81, 9, 49, 16, 36]

// Aggregate
int sum = numbers.Sum();         // 45
int max = numbers.Max();         // 9
double avg = numbers.Average();  // 5.0

LINQ Query Syntax

var result = from n in numbers
             where n > 4
             orderby n descending
             select n;
// [9, 8, 7, 6, 5]

LINQ on Objects

var people = new List<Person> {
    new("Alice", 30),
    new("Bob", 25),
    new("Charlie", 35),
    new("Dave", 25)
};

// Filter and project
var names = people
    .Where(p => p.Age >= 30)
    .Select(p => p.Name)
    .ToList();
// ["Alice", "Charlie"]

// GroupBy
var byAge = people
    .GroupBy(p => p.Age)
    .Select(g => new { Age = g.Key, Count = g.Count() });
// Age 30: 1, Age 25: 2, Age 35: 1

First, Single, Any, All

var nums = new[] { 1, 2, 3, 4, 5 };

bool hasEven   = nums.Any(n => n % 2 == 0);   // true
bool allPos    = nums.All(n => n > 0);         // true
int first      = nums.First(n => n > 3);       // 4
int? firstOrNull = nums.FirstOrDefault(n => n > 10); // null

Chaining LINQ

var topScorers = students
    .Where(s => s.Score >= 80)
    .OrderByDescending(s => s.Score)
    .Take(3)
    .Select(s => s.Name)
    .ToList();