Syntax
collection.First(predicate)\ncollection.Any(predicate)Examples
First and FirstOrDefault
Retrieving the first matching element, with and without risking an exception.
List<int> numbers = new List<int> { 1, 3, 5, 8, 9 };
int firstEven = numbers.First(n => n % 2 == 0);
Console.WriteLine(firstEven); // 8
int firstNegative = numbers.FirstOrDefault(n => n < 0);
Console.WriteLine(firstNegative); // 0 (default for int) - no exception, no match foundSingle and SingleOrDefault
Expecting exactly one match - throws if there are zero or more than one.
List<string> names = new List<string> { "Fola", "Zain", "Jamal" };
string zain = names.Single(n => n == "Zain");
Console.WriteLine(zain); // Zain
// names.Single(n => n.StartsWith("J")); // fine, only Jamal matches
// names.Single(n => n.Length == 4); // throws! Both "Fola" and "Zain" matchAny and All
Checking whether some or every element satisfies a condition.
List<int> numbers = new List<int> { 2, 4, 6, 8 };
bool hasOdd = numbers.Any(n => n % 2 != 0);
Console.WriteLine(hasOdd); // false
bool allEven = numbers.All(n => n % 2 == 0);
Console.WriteLine(allEven); // true
bool isEmpty = !numbers.Any(); // Any() with no predicate checks for any elements at all
Console.WriteLine(isEmpty); // falseContains
Checking whether a sequence contains a specific value.
List<string> names = new List<string> { "Fola", "Zain", "Jamal" };
Console.WriteLine(names.Contains("Zain")); // true
Console.WriteLine(names.Contains("Amir")); // falseBest practices
- Use the "OrDefault" variants (FirstOrDefault, SingleOrDefault) when a missing match is a normal, expected outcome rather than a bug
- Use Single() specifically when exactly one match is a hard requirement - it deliberately throws if that assumption is ever violated, surfacing bugs early
- Use Any() instead of Count() > 0 to check for existence - Any() can stop as soon as it finds one match, while Count() must potentially scan the whole sequence
- Check for null (or use a pattern like ?? defaultValue) after FirstOrDefault()/SingleOrDefault() on reference types, since the default is null
At a glance
- Purpose
- Applications on the .NET platform
- File extension
- .cs
- Runs in
- .NET runtime
- Usually used with
- .NET SDK and libraries
Specifications & further reading
Related C# documentation
Lambda Expressions
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value, using the => (goes to) operator. Lambdas work with delegate types and functional interfaces like Func<> and Action<>, letting you write inline logic without a full named method. Lambdas are the foundation that makes LINQ's fluent, expressive query syntax possible.LINQ Basics: Where & Select
LINQ (Language Integrated Query) provides a consistent, declarative way to query collections, databases, and XML directly within C# syntax. Where() filters a sequence down to elements matching a condition, and Select() transforms each element into something new (a projection). Both are 'lazy' - they build a query that only actually runs when you iterate over the result or call something like ToList().LINQ Ordering & Grouping
OrderBy() and OrderByDescending() sort a sequence by a key you specify, with ThenBy() for secondary sort keys on ties. GroupBy() splits a sequence into groups based on a key selector, producing a sequence of groups where each group itself is enumerable and has a Key property identifying which group it represents.LINQ Aggregation: Sum, Count, Average
LINQ provides built-in aggregation methods that reduce a sequence down to a single summary value: Count() for the number of elements, Sum() for a total, Average() for the mean, and Max()/Min() for extremes. Aggregate() is the general-purpose version, letting you define fully custom accumulation logic when the built-in methods aren't enough.
A lambda expression is a compact way to represent an anonymous function - a block of code that can be passed around as a value, using the => (goes to) operator. Lambdas work with delegate types and functional interfaces like Func<> and Action<>, letting you write inline logic without a full named method. Lambdas are the foundation that makes LINQ's fluent, expressive query syntax possible.LINQ Basics: Where & Select
LINQ (Language Integrated Query) provides a consistent, declarative way to query collections, databases, and XML directly within C# syntax. Where() filters a sequence down to elements matching a condition, and Select() transforms each element into something new (a projection). Both are 'lazy' - they build a query that only actually runs when you iterate over the result or call something like ToList().LINQ Ordering & Grouping
OrderBy() and OrderByDescending() sort a sequence by a key you specify, with ThenBy() for secondary sort keys on ties. GroupBy() splits a sequence into groups based on a key selector, producing a sequence of groups where each group itself is enumerable and has a Key property identifying which group it represents.LINQ Aggregation: Sum, Count, Average
LINQ provides built-in aggregation methods that reduce a sequence down to a single summary value: Count() for the number of elements, Sum() for a total, Average() for the mean, and Max()/Min() for extremes. Aggregate() is the general-purpose version, letting you define fully custom accumulation logic when the built-in methods aren't enough.