First and Single
Learn to get a single element with First, FirstOrDefault and Single.
First element with First
The First method returns the first element of a collection. With a condition, it returns the first element that matches: numbers.First(n => n > 5). If no element matches, it throws InvalidOperationException.
The safe variant is FirstOrDefault: when no element matches, it returns the type's default value (0 for numbers, null for references). Instead of Where followed by First, calling First(condition) directly is shorter and more efficient.
Single element with Single
The Single method assumes the collection has exactly one element. It throws if there are zero or two-or-more elements. With a condition, it expects exactly one element to match.
SingleOrDefault returns the default when no element matches; but it still throws when two or more match. Use Single when you want to guarantee uniqueness, such as finding one record by a unique id.
Exercise Find the first even number
Find the first even number in numbers with First and print it with Console.WriteLine. Even: n % 2 == 0.
Show example solution
Get the first even with numbers.First(n => n % 2 == 0), print with Console.WriteLine.
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 3, 5, 8, 9 };
var first = numbers.First(n => n % 2 == 0);
Console.WriteLine(first);
}
}
Test yourself
-
What does First do on an empty collection?
new int[0].First();- Returns 0
- Returns null
- Throws InvalidOperationException
- Returns false
Show answer
Returns null — Correct. First throws InvalidOperationException on an empty collection; the safe variant is FirstOrDefault.
-
Complete the conditional First
var big = numbers.____(n => n > 100);Show answer
var big = numbers.First(n => n > 100); -
Match each method to its behavior
- First
- Gets the first element
- FirstOrDefault
- Default if missing
- Single
- Exactly one element
- SingleOrDefault
- One or default