Events in C# :👈 👉:File I/O in C#

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

πŸ”™
Events in C# :👈 👉:File I/O in C#