LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3722 min read

LINQ

Learn Language Integrated Query (LINQ) — a powerful, expressive way to query collections in C#.

What is LINQ?

LINQ (Language Integrated Query) lets you query collections, databases, and XML using a consistent, expressive syntax directly inside C#, instead of writing manual loops.

Filtering with Where

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (int n in evenNumbers)
{
Console.Write(n + " ");
}
Output

Click Run to see what this code prints.

Projecting with Select

`Select` transforms each element into something new — a classic "map" operation.

List<string> names = new List<string> { "alice", "bob", "charlie" };
var capitalized = names.Select(n => char.ToUpper(n[0]) + n.Substring(1));
Console.WriteLine(string.Join(", ", capitalized));
Output

Click Run to see what this code prints.

Sorting and Aggregating

List<int> scores = new List<int> { 85, 92, 60, 77, 95 };
var sorted = scores.OrderByDescending(s => s);
int highest = scores.Max();
double average = scores.Average();
int passingCount = scores.Count(s => s >= 70);
Console.WriteLine(string.Join(", ", sorted));
Console.WriteLine($"Max: {highest}, Avg: {average:F1}, Passing: {passingCount}");
Output

Click Run to see what this code prints.

Query Syntax

LINQ also offers a SQL-like "query syntax" as an alternative to the method syntax you've seen so far. Both compile to the same result — method syntax is more common in modern C# code.

var result = from n in numbers
where n % 2 == 0
select n;
// equivalent to:
var result2 = numbers.Where(n => n % 2 == 0);

FAQs

Yes — this is exactly what Entity Framework Core (covered later in this course) uses to translate C# LINQ queries into SQL automatically.

Summary

  • LINQ provides a consistent, expressive way to query collections.
  • Where filters, Select transforms, OrderBy sorts, and Max/Average/Count aggregate.
  • LINQ works identically over in-memory collections and, via EF Core, databases.
Next Lesson →

File Handling