LINQ (Language Integrated Query) — Complete Guide
Date: 2025-08-11 Author: Generated by ChatGPT
LINQ (Language Integrated Query) — Complete Guide 2025-08-11 Generated by ChatGPT
Table of Contents 1. Introduction 2. LINQ Basics - What is LINQ? - LINQ Providers 3. Query
Syntax vs Method Syntax - Query Expression Examples - Method (Fluent) Syntax Examples 4.
Deferred vs Immediate Execution 5. Common LINQ Operators - Filtering: Where - Projection:
Select - Ordering: OrderBy / ThenBy - Joining: Join, GroupJoin - Grouping: GroupBy - Set
operations: Distinct, Union, Intersect, Except - Quantifiers: Any, All, Contains -
Aggregation: Count, Sum, Min, Max, Average, Aggregate - Element operators: First, FirstOrDefault,
Single, SingleOrDefault, ElementAt - Partitioning: Skip, Take, SkipWhile, TakeWhile -
Conversion: ToList, ToArray, ToDictionary, AsEnumerable, AsQueryable 6. LINQ to Objects vs LINQ to
SQL/Entities vs LINQ to XML 7. Expression Trees and IQueryable 8. Performance Considerations & Best
Practices 9. Advanced Topics - Custom extension methods - Deferred execution caveats with
closures - Combining predicates - Grouping into lookups - Using SelectMany for flattening
10. Async and Parallel LINQ (PLINQ) 11. Common Pitfalls & How to Avoid Them 12. Practical Examples
13. Exercises 14. References
1. Introduction LINQ (Language Integrated Query) is a set of features in .NET that adds query
capabilities directly into the C# (and other .NET languages) syntax. It provides a consistent model
for working with data across various kinds of sources (in-memory objects, databases, XML, etc.).
2. LINQ Basics What is LINQ? - LINQ enables querying over enumerable collections in a declarative
way. - It integrates query expressions into the language so you can write concise, readable queries.
LINQ Providers - LINQ to Objects: queries in-memory collections (IEnumerable<T>). - LINQ to SQL /
Entity Framework (LINQ to Entities): translates queries into SQL to run against a database
(IQueryable<T>). - LINQ to XML: querying and manipulating XML. - Other providers: LINQ to DataSet,
LINQ to CSV (third-party), etc.
3. Query Syntax vs Method Syntax Query expressions are reminiscent of SQL and use keywords like
from, where, select. Method syntax uses extension methods and lambdas (fluent style).
Example: Query syntax var result = from p in products where p.Price > 100
orderby p.Name select new { p.Id, p.Name, p.Price };
Equivalent method syntax var result = products .Where(p => p.Price > 100) .OrderBy(p =>
p.Name) .Select(p => new { p.Id, p.Name, p.Price });
Both compile to the same intermediate form; choose whichever improves readability.
4. Deferred vs Immediate Execution - Deferred execution: query execution is delayed until you
iterate over the result (e.g., foreach) or call a terminal operator (ToList, ToArray, Count). -
Immediate execution: operators like ToList, ToArray, Count, Sum, First force immediate execution.
Example: var q = products.Where(p => p.InStock); // no execution yet var list = q.ToList(); //
executes now
5. Common LINQ Operators Filtering: Where var cheap = products.Where(p => p.Price < 50);
Projection: Select var names = products.Select(p => p.Name);
Ordering: OrderBy / ThenBy / OrderByDescending var ordered = products.OrderBy(p =>
p.Category).ThenByDescending(p => p.Price);
Joining: Join var joined = from o in orders join c in customers on o.CustomerId equals
c.Id select new { o.Id, CustomerName = c.Name };
Grouping: GroupBy var grouped = products.GroupBy(p => p.Category);
Set operations var distinctCats = products.Select(p => p.Category).Distinct();
Quantifiers bool anyExpensive = products.Any(p => p.Price > 1000);
Aggregation int total = products.Sum(p => p.Quantity);
Element operators var first = products.FirstOrDefault();
Partitioning var top5 = products.OrderByDescending(p => p.Sales).Take(5);
Conversion var arr = products.ToArray();
6. LINQ to Objects vs LINQ to SQL/Entities vs LINQ to XML - LINQ to Objects executes in the CLR and
uses delegates/lambdas. - LINQ to Entities translates expression trees to SQL — only a subset of
.NET methods can be translated. - LINQ to XML operates on XDocument/XElement and offers functional-
style XML manipulation.
7. Expression Trees and IQueryable - IQueryable<T> represents a query that can be translated and
executed by a provider. - Expression trees capture the structure of code as data
(System.Linq.Expressions.Expression). - Example: Entity Framework reads expression trees and
converts them into SQL.
8. Performance Considerations & Best Practices - Use projection (Select) to fetch only necessary
fields when querying databases. - Beware of N+1 query problem: eager load related data where
appropriate (Include in EF). - When using large collections in memory, consider streaming and avoid
ToList unless necessary. - Combine filters before materialization. - For databases, inspect
generated SQL for efficiency and indexes. - Prefer compiled queries for frequently executed queries
in some ORMs.
9. Advanced Topics Custom extension methods public static IEnumerable<T> MyFilter<T>(this
IEnumerable<T> source, Func<T,bool> predicate) { ... }
Deferred execution with closures for (int i = 0; i < 3; i++) { funcs.Add(() => i); } // captures i
by reference
Combining predicates Expression<Func<T,bool>> pred = a => a.IsActive; pred = pred.And(b => b.Age >
18); // use Expression combiner utilities
Grouping into lookups var lookup = products.ToLookup(p => p.Category);
SelectMany for flattening var words = sentences.SelectMany(s => s.Split(' '));
10. Async and Parallel LINQ (PLINQ) - PLINQ: AsParallel() can speed up CPU-bound operations on large
collections. - AsParallel().WithDegreeOfParallelism(n) - Use async/await for I/O-bound database
queries (e.g., ToListAsync in EF Core).
11. Common Pitfalls & How to Avoid Them - Expecting LINQ to SQL to support every CLR method (it
won't). - Multiple enumeration of an IEnumerable that causes re-execution — materialize with ToList
if needed. - Capturing loop variables in closures (use local copy). - Using .Result or .Wait on
async queries — prefer async all the way.
12. Practical Examples // Example models public class Product { public int Id { get; set; }
public string Name { get; set; } public string Category { get; set; } public decimal Price {
get; set; } public int Quantity { get; set; } }
// Sample usage var products = new List<Product> { new Product { Id = 1, Name = "Pen", Category
= "Stationery", Price = 1.5m, Quantity = 100 }, new Product { Id = 2, Name = "Notebook",
Category = "Stationery", Price = 3.0m, Quantity = 200 }, new Product { Id = 3, Name = "Coffee",
Category = "Beverage", Price = 5.5m, Quantity = 50 }, };
// Query: Top selling categories total value var report = products .GroupBy(p => p.Category)
.Select(g => new { Category = g.Key, TotalValue = g.Sum(x => x.Price * x.Quantity),
Count = g.Count() }) .OrderByDescending(x => x.TotalValue) .ToList();
13. Exercises 1. Write a LINQ query to find the top 3 most expensive products. 2. Given orders and
customers, write a left outer join to include customers with no orders. 3. Using EF Core, write an
efficient query to fetch customers with their last 3 orders. 4. Implement a reusable expression
combiner to chain multiple filters.
14. References - Microsoft Docs: LINQ (Language-Integrated Query) - C# Programming Guide: LINQ -
Entity Framework Core Documentation
--- End of document ---