Lesson 43 +10 XP

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

MethodWhat it does
Wherefilter items by a condition
Selectproject each item into a new form
OrderBy / OrderByDescendingsort
First / FirstOrDefaultget the first match
Countnumber of items
Sum, Average, Max, Minaggregates
Distinctremove duplicates
Any / Alldo 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, Sum are common.
  • Lambda expressions x => ... power the method syntax.
  • Add using System.Linq; first.