C# LINQ

LINQ (Language Integrated Query) lets you query collections with a clean, SQL-like syntax directly in C#. It works on arrays, lists, dictionaries, databases, XML — anything that implements IEnumerable<T>.

Query Syntax

SQL-like — reads top-to-bottom:

CSHARP
var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens = from n in numbers
            where n % 2 == 0
            orderby n descending
            select n;

foreach (var n in evens)
    Console.Write($"{n} "); // 10 8 6 4 2

Method Syntax (Fluent)

The same query with chained methods — more common in practice:

CSHARP
var evens = numbers
    .Where(n => n % 2 == 0)
    .OrderByDescending(n => n)
    .ToList();

Both syntaxes produce identical output — use whichever reads better.

Common Operations

Filtering

CSHARP
var students = new List<Student>
{
    new("Ram", 85),
    new("Sita", 92),
    new("Hari", 78),
    new("Gita", 45),
};

var passing = students.Where(s => s.Score >= 50).ToList();
var topStudents = students.Where(s => s.Score >= 80).ToList();

Transforming (Select)

CSHARP
var names = students.Select(s => s.Name).ToList();
// ["Ram", "Sita", "Hari", "Gita"]

var summaries = students.Select(s => $"{s.Name}: {s.Score}%").ToList();

Sorting

CSHARP
var sorted = students
    .OrderByDescending(s => s.Score)   // primary sort
    .ThenBy(s => s.Name)               // secondary sort
    .ToList();

Aggregate Operations

CSHARP
int sum = numbers.Sum();           // 55
double avg = numbers.Average();    // 5.5
int max = numbers.Max();           // 10
int min = numbers.Min();           // 1
int count = numbers.Count();       // 10

First, Last, Single

CSHARP
var first = students.First(s => s.Score >= 90);      // Sita (throws if none)
var last = students.LastOrDefault(s => s.Score < 50); // null if none
var one = students.Single(s => s.Name == "Ram");      // throws if 0 or 2+

Any, All, Contains

CSHARP
bool anyFailed = students.Any(s => s.Score < 40);    // false
bool allPassed = students.All(s => s.Score >= 50);    // false
bool hasRam = students.Any(s => s.Name == "Ram");     // true

Grouping

CSHARP
var groups = students
    .GroupBy(s => s.Score >= 80 ? "Top" : "Needs work")
    .ToList();

foreach (var group in groups)
{
    Console.WriteLine($"{group.Key}: {string.Join(", ", group.Select(s => s.Name))}");
}
// Top: Ram, Sita
// Needs work: Hari, Gita

Distinct

CSHARP
var unique = numbers.Distinct().ToList();

Chaining

LINQ methods chain — each one transforms the result of the previous:

CSHARP
var result = students
    .Where(s => s.Score >= 50)           // filter
    .OrderByDescending(s => s.Score)     // sort
    .Select(s => s.Name)                 // transform
    .Take(3)                             // first 3
    .ToList();

Tips

  • Prefer method syntax — it is more common and chains naturally.
  • Use FirstOrDefault instead of First when the element might not exist.
  • LINQ is lazy — it does not execute until you iterate or call ToList().
  • For database queries, use IQueryable — LINQ translates it to SQL.

Next: you have completed the C# course! The next step is to build a project — a console app, a web API, or a Unity game.