๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 9 of 40
Lesson 9 of 40 Core C# Intermediate โฑ 40 min

LINQ โ€” Language Integrated Query

Query any data source with LINQ โ€” from in-memory collections to databases. Master filtering, projection, grouping, joining, and deferred execution.

Part 1: LINQ Syntax Styles

var numbers = new[] {1,2,3,4,5,6,7,8,9,10};

// Method syntax (preferred in modern C#)
var evens = numbers.Where(n => n % 2 == 0)
                .Select(n => n * 2);

// Query syntax (SQL-like)
var evens2 = from n in numbers
             where n % 2 == 0
             select n * 2;

Part 2: Key LINQ Operators

var orders = GetOrders();

// Filtering + ordering
var recent = orders.Where(o => o.Total > 100)
                 .OrderByDescending(o => o.Date)
                 .Take(10);

// Projection
var summaries = orders.Select(o => new { o.Id, o.Total });

// Aggregates
decimal total = orders.Sum(o => o.Total);
decimal avg = orders.Average(o => o.Total);

Part 3: GroupBy & Join

// GroupBy
var byStatus = orders
    .GroupBy(o => o.Status)
    .Select(g => new { Status = g.Key, Count = g.Count() });

// Join
var result = orders.Join(customers,
    o => o.CustomerId,
    c => c.Id,
    (o, c) => new { c.Name, o.Total });

Part 4: Deferred Execution

LINQ queries are lazy โ€” they don't execute until you iterate or materialize:
var query = numbers.Where(n => n > 3); // Not executed yet!

// Execute now โ€” force materialisation
var list = query.ToList(); // List<int>
var arr = query.ToArray(); // int[]
int count = query.Count(); // Executes

C# in Visual Studio 2026

๐Ÿ“˜ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition