π LINQ (Language Integrated Query) in C#
LINQ allows querying collections like arrays, lists, XML, and databases using a consistent, readable syntax directly within C#. It bridges the gap between data and code.
π Types of LINQ
- LINQ to Objects: Queries in-memory collections.
- LINQ to SQL: Queries relational databases.
- LINQ to XML: Queries and manipulates XML data.
- LINQ to Entities: Works with Entity Framework.
- LINQ to DataSet: Queries ADO.NET DataSets.
π§ͺ Examples
πΉ LINQ to Objects
int[] numbers = { 1, 2, 3, 4, 5 };
var even = numbers.Where(n => n % 2 == 0);
foreach (var n in even) Console.WriteLine(n); // Output: 2, 4
πΉ LINQ to SQL
var query = from c in db.Customers
where c.City == "Hyderabad"
select c;
πΉ LINQ to XML
XElement xml = XElement.Parse("");
var names = from p in xml.Elements("Person")
select p.Attribute("Name").Value;
πΉ LINQ to Entities
var students = context.Students.Where(s => s.Age > 18);
πΉ LINQ to DataSet
var rows = from r in ds.Tables["Users"].AsEnumerable()
where r.Field<int>("Age") > 20
select r;
β
Best Practices
- Use method syntax for concise queries; use query syntax for readability.
- Apply ToList() or ToArray() only when necessary to avoid premature execution.
- Use deferred execution wiselyβunderstand when queries are evaluated.
- Chain methods like
Where, Select, OrderBy for clean logic.
- Use let in query syntax to simplify complex expressions.
π When to Use
- For querying collections, databases, or XML in a readable way.
- When you need filtering, projection, sorting, grouping operations.
- To reduce boilerplate code and improve maintainability.
- In functional-style programming or data transformation pipelines.
π« When Not to Use
- In performance-critical loopsβLINQ may add overhead.
- When you need fine-grained control over iteration or memory.
- For complex joins or queries better handled by raw SQL.
- In scenarios where deferred execution causes unexpected behavior.
β οΈ Precautions
- Understand deferred vs immediate execution to avoid bugs.
- Be cautious with multiple enumerationsβcan lead to performance issues.
- Donβt overuse
ToList()βit forces execution and may waste memory.
- Use AsEnumerable() to switch from database to in-memory processing when needed.
π― Advantages
- Unified syntax: Works across different data sources.
- Type safety: Compile-time checking of queries.
- Readability: Declarative and expressive code.
- Productivity: Reduces boilerplate and improves maintainability.
- Extensibility: Easily integrates with custom collections and query providers.
π§Ύ LINQ Cheat Sheet (C#)
π¦ Setup
using System;
using System.Linq;
using System.Collections.Generic;
π Filtering
// Query Syntax
var result = from x in list
where x > 10
select x;
// Method Syntax
var result = list.Where(x => x > 10);
π― Projection (Select)
var names = people.Select(p => p.Name);
π Sorting
var sorted = list.OrderBy(x => x);
var sortedDesc = list.OrderByDescending(x => x);
π Grouping
var grouped = from p in people
group p by p.City;
var grouped = people.GroupBy(p => p.City);
π Joining
var join = from a in authors
join b in books on a.Id equals b.AuthorId
select new { a.Name, b.Title };
var join = authors.Join(books,
a => a.Id,
b => b.AuthorId,
(a, b) => new { a.Name, b.Title });
π Aggregation
var count = list.Count();
var sum = list.Sum();
var avg = list.Average();
var min = list.Min();
var max = list.Max();
π Set Operations
var distinct = list.Distinct();
var union = list1.Union(list2);
var intersect = list1.Intersect(list2);
var except = list1.Except(list2);
π Quantifiers
var any = list.Any(x => x > 10);
var all = list.All(x => x > 0);
π¦ Partitioning
var top3 = list.Take(3);
var skip2 = list.Skip(2);
π Conversion
var array = list.ToArray();
var listAgain = list.ToList();
var dict = list.ToDictionary(x => x.Key);
π§ͺ Element Operators
var first = list.First();
var firstOrDefault = list.FirstOrDefault();
var single = list.Single(x => x.Id == 1);
var elementAt = list.ElementAt(2);
π Notes
- Use query syntax for readability, especially with joins and groups.
- Use method syntax for chaining and lambda flexibility.
- LINQ is deferred executionβqueries run when enumerated.
π Conclusion
LINQ transforms how developers query and manipulate data in C#. With its expressive syntax and powerful capabilities, itβs a must-have tool for modern .NET development. Use it wisely to write clean, efficient, and maintainable code.