Roadmap › LINQ — Language Integrated Query › Module: LINQ Basics
Lessons in this course (12)
4. Element, quantifier and partitioning operators
Basic★ Must knowLesson 4 of 12
| Operator | Empty sequence | More than one match |
|---|---|---|
First() | throws | returns first |
FirstOrDefault() | default/null | returns first |
Single() | throws | throws |
SingleOrDefault() | default/null | throws |
Last() / LastOrDefault() | throws / default | returns last |
ElementAt(i) / ElementAtOrDefault(i) | throws / default | — |
csharp
bool anyOut = products.Any(p => p.Stock == 0); // stops at first match
bool allPriced = products.All(p => p.Price > 0);
bool hasMouse = products.Select(p => p.Name).Contains("Mouse");
var page2 = products.OrderBy(p => p.Id).Skip(10).Take(10);
var whileCheap = products.OrderBy(p => p.Price).TakeWhile(p => p.Price < 10000);
foreach (var batch in products.Chunk(100)) { /* process 100 at a time (.NET 6) */ }
var cheapest = products.MinBy(p => p.Price); // .NET 6 — returns the element, not the valueUse Any() instead of Count() > 0 — Any stops at the first element.