LINQ (Language Integrated Query) lets you query collections with SQL-like expressions right inside C#. Instead of writing loops and if-statements to filter or sort data, you write a query and LINQ handles the rest.
Setting Up LINQ
Add using System.Linq; at the top. This brings in all the LINQ extension methods so you can use them on any collection.
using System.Linq;
Where โ Filtering
Where lets you filter items based on a condition. Give it a lambda expression, and it returns only the items that match.
List numbers = new List { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (int n in evenNumbers)
{
Console.WriteLine(n);
}
Try it Yourself โ
Select โ Transforming
Select transforms each item into something else. Square each number, extract names from objects, you name it.
List numbers = new List { 1, 2, 3 };
var squares = numbers.Select(n => n * n);
foreach (int s in squares)
{
Console.WriteLine(s);
}
OrderBy โ Sorting
OrderBy sorts in ascending order. Use OrderByDescending for the reverse.
List names = new List { "Charlie", "Alice", "Bob" };
var sorted = names.OrderBy(n => n);
foreach (string name in sorted)
{
Console.WriteLine(name);
}
ToList โ Materializing
LINQ methods return IEnumerable<T>, which means the query hasn't run yet โ it's lazy. Call ToList() to execute the query and store results in a list.
List numbers = new List { 5, 2, 8, 1, 9 };
List sortedList = numbers.OrderBy(n => n).ToList();
Query Syntax vs Method Syntax
LINQ has two flavors. Method syntax uses extension methods with lambdas (what we've been doing). Query syntax looks more like SQL.
List numbers = new List { 1, 2, 3, 4, 5, 6 };
var methodSyntax = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
var querySyntax = from n in numbers
where n % 2 == 0
orderby n
select n;
Both produce the same result. Method syntax is more common in professional C#, but query syntax can be easier to read for complex queries. Pick whichever feels natural.
Chaining
You can chain LINQ methods together to build powerful queries in one line.
List numbers = new List { 5, 2, 8, 1, 9, 3 };
var result = numbers
.Where(n => n > 3)
.OrderByDescending(n => n)
.Select(n => n * 10)
.ToList();
foreach (int n in result)
{
Console.WriteLine(n);
}