C# LINQ Chaining with Method Syntax

C# LINQ Chaining with Method Syntax

C# LINQ Chaining with Method Syntax

Common LINQ patterns using method syntax (preferred over query syntax for most cases).

var orders = GetOrders(); // IEnumerable<Order>

// Filter + project
var recent = orders
    .Where(o => o.CreatedAt >= DateTime.UtcNow.AddDays(-30))
    .Select(o => new { o.Id, o.Total, o.CustomerName })
    .OrderByDescending(o => o.Total)
    .Take(10)
    .ToList();

// Group and aggregate
var byRegion = orders
    .GroupBy(o => o.Region)
    .Select(g => new
    {
        Region = g.Key,
        Count  = g.Count(),
        Total  = g.Sum(o => o.Total),
        Avg    = g.Average(o => o.Total),
    })
    .OrderByDescending(x => x.Total);

// Flatten nested collections
var allItems = orders
    .SelectMany(o => o.Items)
    .Where(i => i.Quantity > 1)
    .ToList();

// First or default with fallback
var vip = orders
    .Where(o => o.Total > 1000)
    .MaxBy(o => o.Total);
All Comments