Let’s go through LINQ queries in C# β€” a powerful way to query collections in a readable, SQL-like style.


πŸ“Œ 1. What is LINQ?

  • LINQ (Language-Integrated Query) is a feature in C# that allows you to query collections (arrays, lists, XML, databases) using C# syntax.

  • Provides type safety and intelliSense support in Visual Studio.


πŸ“Œ 2. LINQ Syntaxes

There are two main syntaxes:

  1. Query Syntax (SQL-like)

  2. Method Syntax (Fluent API / Lambda expressions)


πŸ“Œ 3. Query Syntax Example

using System;
using System.Linq;
using System.Collections.Generic;
 
int[] numbers = { 1, 2, 3, 4, 5, 6 };
 
// Get even numbers
var evenNumbers = from n in numbers
                  where n % 2 == 0
                  select n;
 
foreach (var n in evenNumbers)
    Console.WriteLine(n); // 2, 4, 6
  • from β†’ data source

  • where β†’ filter condition

  • select β†’ projection of data


πŸ“Œ 4. Method Syntax Example

var evenNumbers = numbers.Where(n => n % 2 == 0).Select(n => n);
 
foreach (var n in evenNumbers)
    Console.WriteLine(n); // 2, 4, 6
  • Uses lambda expressions for filtering and selecting

  • Method chaining allows for concise and readable queries


πŸ“Œ 5. Common LINQ Methods

MethodDescription
Where(predicate)Filters elements
Select(selector)Projects elements (like map)
OrderBy(key)Sort ascending
OrderByDescending(key)Sort descending
First() / FirstOrDefault()Get first element (or default)
Any() / All()Check conditions
Count()Number of elements
Distinct()Remove duplicates
Sum(), Average()Aggregation

πŸ“Œ 6. Example with Objects

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}
 
List<Student> students = new List<Student>
{
    new Student { Name = "Alice", Age = 20 },
    new Student { Name = "Bob", Age = 22 },
    new Student { Name = "Charlie", Age = 21 }
};
 
// Query students older than 20
var result = from s in students
             where s.Age > 20
             select s.Name;
 
foreach (var name in result)
    Console.WriteLine(name); // Bob, Charlie
  • Works on any collection implementing IEnumerable<T>

πŸ“Œ 7. LINQ Advantages

  1. Readable β†’ SQL-like syntax in C#

  2. Consistent β†’ Works on arrays, lists, XML, databases

  3. Type-safe β†’ Compile-time checking

  4. Concise β†’ No need for loops and manual filtering


πŸ“Œ 8. Summary Table

SyntaxDescription
Query SyntaxSQL-like: from ... in ... where ... select ...
Method SyntaxLambda-based: .Where(...).Select(...)
Common MethodsWhere, Select, OrderBy, First, Any, Count
AdvantagesReadability, consistency, type safety, concise

βœ… Tip:

  • Use query syntax for readability (especially with complex queries)

  • Use method syntax for lambda-based chaining and inline functions

  • LINQ works seamlessly with arrays, lists, dictionaries, XML, and databases (Entity Framework)