C# Reference ยท LINQ
LINQ overview
A reference overview of LINQ in C#: how queries over IEnumerable work, method vs query syntax, deferred execution, the operator families and when not to use it.
LINQ (Language Integrated Query) is a set of methods and a query syntax for working with sequences of data. You describe what you want (filter these, sort by that, group by this, add them up) and LINQ builds the result. The same operators work on arrays, lists, dictionaries, XML, databases (through providers such as Entity Framework) and anything else that implements IEnumerable<T> or IQueryable<T>.
The operators are extension methods in System.Linq.Enumerable (for in-memory sequences) and System.Linq.Queryable (for providers that translate queries). The runner's implicit global usings already include System.Linq.
int[] numbers = [5, 8, 2, 9, 4]; var result = numbers.Where(n => n > 3).OrderBy(n => n).Select(n => n * 10); // 40, 50, 80, 90
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
IEnumerable<TResult> query = source.Operator(lambda); // method syntax var query2 = from x in source where cond select x; // query syntax
| Family | Operators |
|---|---|
| Filtering | Where, OfType, Distinct, Take, Skip, TakeWhile, SkipWhile |
| Projection | Select, SelectMany, Zip, Index |
| Ordering | OrderBy, ThenBy, OrderByDescending, Order, Reverse |
| Grouping and joining | GroupBy, Join, GroupJoin, CountBy, AggregateBy, ToLookup |
| Aggregation | Count, Sum, Average, Min, Max, MinBy, MaxBy, Aggregate |
| Quantifiers | Any, All, Contains, SequenceEqual |
| Element access | First, FirstOrDefault, Single, Last, ElementAt |
| Set operations | Union, Intersect, Except, Concat, Append, Prepend |
| Conversion | ToList, ToArray, ToDictionary, ToHashSet, Cast, AsEnumerable |
| Generation | Range, Repeat, Empty |
Returns: operators that return IEnumerable<T> are lazy (deferred). Operators that return a value, array or collection run the query immediately.
Errors: a null source throws ArgumentNullException immediately for most operators. First/Single throw InvalidOperationException when the sequence is empty (and Single when it has more than one match).
Usage notes
- Query syntax compiles to the method calls, and the two mix well: wrap a query in parentheses and call
.ToList()on it. Some operators (Take,Skip,Distinct,Count) exist only as methods. - Deferred execution means a query runs every time you enumerate it and sees the data as it is at that moment. Materialize with
ToList()orToArray()when you need a snapshot or you will enumerate more than once. - LINQ to Objects works on
IEnumerable<T>with delegates; LINQ to Entities works onIQueryable<T>with expression trees that become SQL. Only some C# expressions can be translated. - Many operators are optimized:
Count()on a list reads itsCount, andElementAton anIList<T>indexes directly. - LINQ allocates enumerators and closures. It is fine for most code; for hot loops measure first and consider
for/foreachloops or spans. - Do not mutate the source while a query is being enumerated (see modifying while enumerating).
- Side effects inside
WhereandSelectrun at enumeration time, perhaps several times or not at all. Keep lambdas pure.
Related
- Where() and Select()
- Deferred execution
- Query syntax
- LINQ performance
- LINQ basics and LINQ operators in the tutorial