๐ 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.