Core Features

LINQ

Query and transform data with LINQ — one of C#'s most powerful and distinctive features.

What is LINQ?

LINQ (Language Integrated Query) lets you query data sources — lists, arrays, databases, XML — using familiar C# syntax.

Two Syntax Styles

Query syntax (SQL-like):

csharp
var result = from item in collection where item.Age > 18 select item;

Method syntax (lambda-based, more commonly used):

csharp
var result = collection.Where(item => item.Age > 18);

Deferred Execution

LINQ queries are lazy — they don't execute until you iterate (foreach) or call a materializing method (ToList, Count, First, etc.).

Example

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

record Product(int Id, string Name, decimal Price, string Category, int Stock);

var products = new List<Product> {
    new(1, "Laptop", 999.99m, "Electronics", 50),
    new(2, "Phone", 599.99m, "Electronics", 120),
    new(3, "Desk", 299.99m, "Furniture", 30),
    new(4, "Chair", 199.99m, "Furniture", 45),
    new(5, "Tablet", 449.99m, "Electronics", 80),
};

// Filter
var electronics = products.Where(p => p.Category == "Electronics");

// Select (project/transform)
var names = products.Select(p => p.Name);
var summaries = products.Select(p => new { p.Name, p.Price });

// Order
var byPrice = products.OrderBy(p => p.Price);
var expensiveFirst = products.OrderByDescending(p => p.Price);

// Aggregate
decimal totalValue = products.Sum(p => p.Price * p.Stock);
decimal avgPrice = products.Average(p => p.Price);
decimal maxPrice = products.Max(p => p.Price);

// Group
var byCategory = products.GroupBy(p => p.Category);
foreach (var group in byCategory) {
    Console.WriteLine($"{group.Key}: {group.Count()} products");
    Console.WriteLine($"  Total value: {group.Sum(p => p.Price * p.Stock):C}");
}

// Chain operations
var result = products
    .Where(p => p.Price > 300)
    .OrderBy(p => p.Price)
    .Select(p => $"{p.Name}: {p.Price:C}")
    .ToList();

result.ForEach(Console.WriteLine);

// First, Single, Any, All, Count
var cheapest = products.MinBy(p => p.Price);
bool hasExpensive = products.Any(p => p.Price > 900);
bool allInStock = products.All(p => p.Stock > 0);
int electronicCount = products.Count(p => p.Category == "Electronics");
Try it yourself — CSHARP