Loading lessons...
LINQ (Language Integrated Query)
LINQ (Language Integrated Query)
LINQ lets you query collections with a SQL-like syntax, right inside C#. It turns filtering, sorting, and transforming data into readable code.
The using
Add using System.Linq; to use LINQ methods.
Query syntax
int[] scores = { 90, 71, 82, 93, 75, 82 };
var highScores = from score in scores
where score > 80
select score;
highScores contains 90, 82, 93, 82.
Method syntax (the common way)
The same query with method chaining:
var highScores = scores.Where(score => score > 80);
Common LINQ methods
| Method | What it does |
|---|---|
Where | filter items by a condition |
Select | project each item into a new form |
OrderBy / OrderByDescending | sort |
First / FirstOrDefault | get the first match |
Count | number of items |
Sum, Average, Max, Min | aggregates |
Distinct | remove duplicates |
Any / All | do any/all items match? |
scores.OrderByDescending(s => s); // 93, 90, 82, ...
scores.Where(s => s > 80).Count(); // 4
scores.Max(); // 93
scores.Distinct(); // 90, 71, 82, 93, 75
Lambda expressions
The => arrow is a lambda - a tiny inline function. In Where(s => s > 80), each s is an element, and the expression decides if it's kept.
LINQ works on any collection
Use LINQ with arrays, lists, dictionaries, and more.
TL;DR
- LINQ = querying collections inside C#.
Where,Select,OrderBy,Count,Sumare common.- Lambda expressions
x => ...power the method syntax. - Add
using System.Linq;first.