Skip to main content

How to Get the First Item or a Default with LINQ FirstOrDefault in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

words.FirstOrDefault(word => word.Length > 5) returns the first word that passes the test. When no word passes, you get a default instead of an exception: null for a string, 0 for an int, or a value you pass in.

Microsoft's reference: Returns the first element of the sequence that satisfies a condition or a default value if no such element is found. What that default is depends on the type of the items: The default value for reference and nullable types is null. For a number type such as int, it's 0.

Syntax​

Syntax
T? <first> = <items>.FirstOrDefault();
T? <first> = <items>.FirstOrDefault(<x> => <condition>);
T <first> = <items>.FirstOrDefault(<x> => <condition>, <defaultValue>);
PartWhat it is
<items>Any sequence, such as an array or a List<T>
FirstOrDefault()The first item, or the default when there are no items
<x> => <condition>A test for each item: FirstOrDefault returns the first item that passes
<defaultValue>What to return when no item passes, instead of the type's default
TThe type of the items, such as string or int. For a string, the result is a string?, because it can be null

The Example​

A console app called FirstOrDefault looks through the words sun, planet, moon and galaxy: once for the first word longer than 5 letters, and twice for a word that starts with z, which isn't there. Last, it asks an empty array of numbers for its first item.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n FirstOrDefault
cd FirstOrDefault
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/FirstOrDefault/FirstOrDefault.csproj:
Determining projects to restore...
Restored /Users/you/source/FirstOrDefault/FirstOrDefault.csproj (in 41 ms).
Restore succeeded.

dotnet new console -n FirstOrDefault creates a folder named FirstOrDefault with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or FirstOrDefault.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First a search that finds a word:

Program.cs (a search that finds a word)
// A few words. FirstOrDefault returns the first one that passes the test.
string[] words = ["sun", "planet", "moon", "galaxy"];

string? longWord = words.FirstOrDefault(word => word.Length > 5);
Console.WriteLine($"First word longer than 5 letters: {longWord}");

word => word.Length > 5 is the test. FirstOrDefault tries the words in order and returns planet, the first with more than 5 letters. The result is a string?, a string that can be null, because that's what you get when no word passes.

Then a search that finds nothing:

Program.cs (a search that finds nothing)
// No word starts with z, so FirstOrDefault returns the default for string, which is null.
string? zWord = words.FirstOrDefault(word => word.StartsWith('z'));
Console.WriteLine($"First word that starts with z is null: {zWord is null}");

No word starts with z, so the result is null, the default for string, and zWord is null checks for it.

Then the same search with your own default:

Program.cs (your own default)
// Pass your own default, and you get it instead of null.
string zOrNone = words.FirstOrDefault(word => word.StartsWith('z'), "none");
Console.WriteLine($"With none as the default: {zOrNone}");

The second argument, "none", comes back when no word passes. The result can't be null now, so it's a plain string.

Last, an array of numbers with no items:

Program.cs (an empty array)
// For an int, the default is 0.
int[] noScores = [];
Console.WriteLine($"First item of an empty int array: {noScores.FirstOrDefault()}");

FirstOrDefault() without a test returns the first item, or the default when there's none.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
First word longer than 5 letters: planet
First word that starts with z is null: True
With none as the default: none
First item of an empty int array: 0

macOS-style terminal window titled Terminal — FirstOrDefault showing dotnet run printing First word longer than 5 letters: planet, First word that starts with z is null: True, With none as the default: none and First item of an empty int array: 0

Planet was the first of the four words with more than 5 letters. The search for z found nothing and returned null, and the same search with "none" as the default returned none. The empty int array gave 0, the default for int.

The Complete File​

macOS-style code window titled Program.cs — FirstOrDefault showing an array of the words sun, planet, moon and galaxy, FirstOrDefault with a test for words longer than 5 letters, the same with a test for words that start with z checked with is null, the z search again with none as the default, and FirstOrDefault on an empty int array

Program.cs
// A few words. FirstOrDefault returns the first one that passes the test.
string[] words = ["sun", "planet", "moon", "galaxy"];

string? longWord = words.FirstOrDefault(word => word.Length > 5);
Console.WriteLine($"First word longer than 5 letters: {longWord}");

// No word starts with z, so FirstOrDefault returns the default for string, which is null.
string? zWord = words.FirstOrDefault(word => word.StartsWith('z'));
Console.WriteLine($"First word that starts with z is null: {zWord is null}");

// Pass your own default, and you get it instead of null.
string zOrNone = words.FirstOrDefault(word => word.StartsWith('z'), "none");
Console.WriteLine($"With none as the default: {zOrNone}");

// For an int, the default is 0.
int[] noScores = [];
Console.WriteLine($"First item of an empty int array: {noScores.FirstOrDefault()}");

Common Mistakes​

MistakeWhat happensDo this instead
Using First when nothing may pass the testInvalidOperationException: Sequence contains no matching elementUse FirstOrDefault and check the result. The reference: To instead return a default value when no matching element is found, use the FirstOrDefault method.
Using the result without checking for nullThe build warned warning CS8602: Dereference of a possibly null reference., and zWord.Length threw NullReferenceException: Object reference not set to an instance of an object.Check is null first, or pass a default such as "none"
Treating 0 from an int sequence as "not found"For the scores 0, 7 and 3, the first score below 5 and the first score above 10 both came back as 0Pass a default that can't be a real item: FirstOrDefault(score => score > 10, -1) returned -1

FAQ​

Does FirstOrDefault look at every item?​

No. It stops at the first item that passes. A check counted the calls to the test: it found planet after testing 2 of the 4 words.

Why is the result a nullable string?​

Because it can be null, and the ? in string? says so. Stored in a plain string, the build warned warning CS8600: Converting null literal or possible null value to non-nullable type. With a default of your own, as in the "none" search, the result can't be null, and a plain string is right.

Conclusion​

FirstOrDefault returns the first item that passes your test, or a default when none does: null for a string, 0 for an int, or the value you pass as the second argument. Check the result before you use it, or pass a default that can't be mistaken for a real item.

Additional Resources​