Mastering LINQ Queries in C# .NET (Where, Select, OrderBy)
Query, filter, and transform in-memory collections and database sets in C# with expressive LINQ syntax.
Concepts & Theory
LINQ unifies query syntax across in-memory collections, relational SQL databases (EF Core), and XML/JSON documents.
Most LINQ operators leverage deferred execution: computations occur only upon iteration (e.g. `foreach` or `.ToList()`).
`Where()` filters elements, `Select()` transforms projections, and `OrderBy()` applies sorting logic.
Code Example
Run in Playgroundusing System;
using System.Collections.Generic;
using System.Linq;
public class Developpeur {
public string Nom { get; set; }
public string Langage { get; set; }
public int AnneesExperience { get; set; }
}
public class Program {
public static void Main() {
var devs = new List<Developpeur> {
new Developpeur { Nom = "Alice", Langage = "C#", AnneesExperience = 5 },
new Developpeur { Nom = "Bob", Langage = "Python", AnneesExperience = 2 },
new Developpeur { Nom = "Charlie", Langage = "C#", AnneesExperience = 8 },
};
// Requête LINQ élégante en Method Syntax
var seniorsCSharp = devs
.Where(d => d.Langage == "C#" && d.AnneesExperience >= 5)
.OrderByDescending(d => d.AnneesExperience)
.Select(d => $"{d.Nom} ({d.AnneesExperience} ans)")
.ToList();
foreach (var dev in seniorsCSharp) {
Console.WriteLine(dev);
}
}
}Common Pitfalls & Mistakes
✗ Calling .ToList() repeatedly across chained operators
var res = list.ToList().Where(x => x > 5).ToList();var res = list.Where(x => x > 5).ToList();Each `.ToList()` allocates a new collection in RAM. Chain operators and materialize only once at the end.
Frequently Asked Questions
What is deferred execution in LINQ?▾
It means the query logic is evaluated lazily when results are consumed, not when the query expression is defined.
Master C# with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
