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
OperatorEmpty sequenceMore than one match
First()throwsreturns first
FirstOrDefault()default/nullreturns first
Single()throwsthrows
SingleOrDefault()default/nullthrows
Last() / LastOrDefault()throws / defaultreturns 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 value

Use Any() instead of Count() > 0 — Any stops at the first element.