Back to results for “Streams & Lambdas”
C# › LINQ

What is LINQ, and how does it simplify querying collections compared to writing manual loops?

Intermediate

Answer

LINQ (Language Integrated Query) lets you filter, transform, sort, and aggregate data using a concise, declarative, SQL-like syntax directly in C#, working consistently across in-memory collections (LINQ to Objects), databases via Entity Framework (LINQ to Entities), and XML -- instead of manually writing a loop with conditional logic to build a filtered result, you express the intent directly, and LINQ handles the iteration; a key related concept is deferred execution, where a LINQ query isn't actually run until its results are enumerated (like via ToList() or a foreach), letting the runtime optimize what actually gets executed.
// Manual loop
var evenNumbers = new List<int>();
foreach (var n in numbers) { if (n % 2 == 0) evenNumbers.Add(n); }

// Equivalent LINQ, more concise and declarative
var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

// Deferred execution: no filtering happens until .ToList() is actually called
var query = numbers.Where(n => n > 2);
var result = query.ToList(); // filtering runs HERE, not when 'query' was defined
Real-world example A reporting feature filters and groups a large in-memory list of transactions by category and date range using a single chained LINQ expression, replacing what would otherwise be several nested loops and temporary collections with a few readable lines.

Common follow-ups: What specific LINQ operations (GroupBy, Join, Aggregate) go beyond simple filtering?;Why does deferred execution sometimes cause a query to unexpectedly re-run and produce different results?