*
Previous Events in C# File I/O in C# Next

๐Ÿ” LINQ in C#

๐Ÿ” 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.

Back to Index
Previous Events in C# File I/O in C# Next
*
*