Isaac.

LINQ Deep Dive

Master LINQ for querying and transforming data in .NET applications.

By EMEPublished: February 20, 2025
linqcsharpqueriesenumerableperformance

A Simple Analogy

Imagine organizing a library catalog. Instead of manually walking through shelves, LINQ is like using a powerful search system that lets you filter books by author, sort by date, and transform the results—all with a single query.


What Is LINQ?

LINQ (Language Integrated Query) is a C# feature that provides a unified way to query different data sources (collections, databases, XML) using a SQL-like syntax.


Query Syntax vs. Method Syntax

Query Syntax (SQL-like)

var adults = from person in people
             where person.Age >= 18
             orderby person.Name
             select person;

Method Syntax (Fluent)

var adults = people
    .Where(p => p.Age >= 18)
    .OrderBy(p => p.Name)
    .ToList();

Common LINQ Operators

Filtering

var expensiveProducts = products
    .Where(p => p.Price > 100)
    .ToList();

Ordering

var sorted = people
    .OrderBy(p => p.Age)
    .ThenByDescending(p => p.Name)
    .ToList();

Projection (Select)

var names = people.Select(p => p.Name).ToList();
var details = people.Select(p => new { p.Name, p.Age }).ToList();

Aggregation

int count = numbers.Count();
decimal sum = prices.Sum();
double average = scores.Average();
decimal max = prices.Max();

Grouping

var grouped = people
    .GroupBy(p => p.Department)
    .Select(g => new { Department = g.Key, Count = g.Count() })
    .ToList();

Joins

var result = people
    .Join(orders,
        p => p.Id,
        o => o.PersonId,
        (p, o) => new { p.Name, o.OrderDate })
    .ToList();

Practical Examples

E-commerce Product Filtering

var expensiveInStock = products
    .Where(p => p.Price > 50 && p.Stock > 0)
    .OrderByDescending(p => p.Rating)
    .Select(p => new { p.Name, p.Price, p.Rating })
    .Take(10)
    .ToList();

Data Transformation

var userSummary = users
    .GroupBy(u => u.Country)
    .Select(g => new 
    { 
        Country = g.Key, 
        Total = g.Count(), 
        AgeAverage = g.Average(u => u.Age) 
    })
    .OrderByDescending(x => x.Total)
    .ToList();

Performance Considerations

  • Deferred execution: LINQ is lazy; nothing executes until you call ToList() or iterate
  • Avoid multiple enumerations: Call ToList() once if used multiple times
  • LINQ to Objects vs. LINQ to EF Core: Database queries execute on the server

Related Concepts to Explore

  • LINQ to SQL and Entity Framework
  • Async LINQ operations
  • Expression trees
  • Custom LINQ operators
  • Parallel LINQ (PLINQ)

Summary

LINQ transforms data querying from imperative loops to declarative, readable expressions. Master filtering, ordering, grouping, and joins, and you'll write cleaner, more maintainable C# code.