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:
-
Query Syntax (SQL-like)
-
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
Method | Description |
---|---|
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
-
Readable β SQL-like syntax in C#
-
Consistent β Works on arrays, lists, XML, databases
-
Type-safe β Compile-time checking
-
Concise β No need for loops and manual filtering
π 8. Summary Table
Syntax | Description |
---|---|
Query Syntax | SQL-like: from ... in ... where ... select ... |
Method Syntax | Lambda-based: .Where(...).Select(...) |
Common Methods | Where , Select , OrderBy , First , Any , Count |
Advantages | Readability, 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)