18
Lesson 18 of 35 · OOP

LINQ Queries

LINQ (Language Integrated Query) lets you query collections, databases, and XML using a consistent syntax that looks like SQL. This lesson covers query syntax, method syntax, and the most important LINQ operators.

Query Syntax vs Method Syntax

LINQ has two equivalent styles. Query syntax resembles SQL and is familiar to database developers. Method syntax uses extension methods and lambda expressions and is more powerful.

Both LINQ syntaxes LINQ.cs
int[] nums = { 5, 3, 8, 1, 9, 2, 7, 4, 6 };

// Query syntax
var q1 = from n in nums
         where n > 4
         orderby n
         select n * n;

// Equivalent method syntax
var q2 = nums
    .Where(n => n > 4)
    .OrderBy(n => n)
    .Select(n => n * n);

Console.WriteLine(string.Join(", ", q1)); // 25, 36, 49, 64, 81

Grouping & Aggregation

LINQ can group elements and compute aggregates like Sum, Average, Min, Max, and Count.

Grouping Grouping.cs
var orders = new[]
{
    new { Product = "Apple",  Amount = 3.5 },
    new { Product = "Banana", Amount = 1.2 },
    new { Product = "Apple",  Amount = 2.8 },
};

var byProduct = orders
    .GroupBy(o => o.Product)
    .Select(g => new { Product = g.Key, Total = g.Sum(o => o.Amount) });

foreach (var item in byProduct)
    Console.WriteLine($"{item.Product}: {item.Total:F1}");

Joins & Flattening

Join correlates two sequences by a key. SelectMany flattens nested collections—like a SQL CROSS JOIN or a nested loop.

Join example LINQJoin.cs
var customers = new[] { new { Id=1, Name="Alice" }, new { Id=2, Name="Bob" } };
var orders    = new[] { new { CId=1, Item="Book" }, new { CId=1, Item="Pen" }, new { CId=2, Item="Desk" } };

var joined = customers.Join(orders,
    c => c.Id, o => o.CId,
    (c, o) => $"{c.Name} ordered {o.Item}");

foreach (string line in joined)
    Console.WriteLine(line);