Skip to main content

How to Find the First Matching Item in a List with Find in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

pets.Find(pet => pet.Age > 5) goes through a list from the start and gives you the first item that passes the test. When no item passes, it gives you the type's default value instead: null for a record, 0 for an int.

Find is a method of List<T>. Microsoft's API reference describes it as: Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

The predicate is the test you pass in. The reference explains how Find uses it: The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<T> are individually passed to the Predicate<T> delegate, moving forward in the List<T>, starting with the first element and ending with the last element. Processing is stopped when a match is found.

Syntax​

Syntax
<Type> <found> = <list>.Find(<item> => <condition>);
PartWhat it is
<list>The List<T> to search
FindPasses the items to the test one by one, from the first, and stops at the first one that passes
<item> => <condition>The test, written as a lambda expression
<item>The name the test gives the item it's checking, such as pet
<condition>A bool expression about <item>, such as pet.Age > 5
<Type>The type of the list's items. For a class or a record, add ? (such as Pet?), because the result can be null
<found>The first item that passed, or the type's default value when none did

The Example​

A console app called ListFind keeps a list of three pets: Rex, who is 3, Milo, who is 7, and Bella, who is 9. It finds the first pet older than 5, then looks for a pet older than 20, which isn't there. Last, it runs the same kind of search on a list of plain numbers, to show what Find returns there when nothing matches.

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 ListFind
cd ListFind
Output
The template "Console App" was created successfully.

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

dotnet new console -n ListFind creates a folder named ListFind 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 ListFind.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the list and the search:

Program.cs (the first pet older than 5)
// A list of pets. Find returns the first one that passes the test.
List<Pet> pets = [new("Rex", 3), new("Milo", 7), new("Bella", 9)];

Pet? older = pets.Find(pet => pet.Age > 5);
if (older is not null)
Console.WriteLine($"First pet older than 5: {older.Name}, age {older.Age}");

List<Pet> pets = [...] creates a list with the three pets, in that order. pet => pet.Age > 5 is the test, written as a lambda expression. The C# reference: Use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body. pet is each pet in turn, and pet.Age > 5 is what it must pass. Rex is 3 and fails, Milo is 7 and passes, so Find stops at Milo. The result is a Pet?, with a ?, because it can be null, and if (older is not null) prints only when a pet was found.

Then a test that no pet passes:

Program.cs (no match)
// When no pet passes the test, Find returns null, the default for a record.
Pet? veryOld = pets.Find(pet => pet.Age > 20);
Console.WriteLine($"First pet older than 20 is null: {veryOld is null}");

The reference says what Find returns: The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T. Pet is a record, and the records reference says: A record or a record class declares a reference type. The C# table of default values gives null for Any reference type, so this Find returns null.

Then the same kind of search on numbers:

Program.cs (a list of numbers)
// For a list of numbers, the default is 0.
List<int> ages = [3, 7, 9];
Console.WriteLine($"First age over 20: {ages.Find(age => age > 20)}");

For int, the table of default values gives 0 (zero) for Any built-in integral numeric type, so this Find returns 0. The Find reference warns about that: When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate.

Last, the Pet record, at the end of the file:

Program.cs (the Pet record)
record Pet(string Name, int Age);

One line declares a record with a name and an age, and (string Name, int Age) is its primary constructor. The records reference: When you declare a primary constructor on a record, the compiler generates public properties for the primary constructor parameters. That's where pet.Age and older.Name come from.

Step 3: Run It​

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

Terminal
dotnet run
Output
First pet older than 5: Milo, age 7
First pet older than 20 is null: True
First age over 20: 0

macOS-style terminal window titled Terminal — ListFind showing dotnet run printing First pet older than 5: Milo, age 7, then First pet older than 20 is null: True, then First age over 20: 0

Find returned Milo, age 7, the first pet older than 5. Bella, who is 9, passes the test too, but Find had already stopped at Milo. No pet is older than 20, so the second search returned null and printed True. The list of ages has no number over 20 either, and that search printed 0.

The Complete File​

macOS-style code window titled Program.cs — ListFind showing a list of three pets searched with Find and a lambda test for an age over 5, a second Find that returns null when no pet matches, and a Find on a list of ages that returns 0

Program.cs
// A list of pets. Find returns the first one that passes the test.
List<Pet> pets = [new("Rex", 3), new("Milo", 7), new("Bella", 9)];

Pet? older = pets.Find(pet => pet.Age > 5);
if (older is not null)
Console.WriteLine($"First pet older than 5: {older.Name}, age {older.Age}");

// When no pet passes the test, Find returns null, the default for a record.
Pet? veryOld = pets.Find(pet => pet.Age > 20);
Console.WriteLine($"First pet older than 20 is null: {veryOld is null}");

// For a list of numbers, the default is 0.
List<int> ages = [3, 7, 9];
Console.WriteLine($"First age over 20: {ages.Find(age => age > 20)}");

record Pet(string Name, int Age);

Common Mistakes​

MistakeWhat happensDo this instead
Using the result without checking for nullWith no pet older than 20, the build warned warning CS8602: Dereference of a possibly null reference. and veryOld.Name threw NullReferenceException: Object reference not set to an instance of an object.Check if (older is not null) before you use the result
Using Find on numbers where 0 is a real itemIn the list [-3, 0, 4], Find(t => t > -1) printed 0 because 0 passed, and Find(t => t > 10) printed 0 because nothing didUse FindIndex: it printed 1, the position of the 0, for the first test and -1 for the second
Passing the item instead of a testnames.Find("Milo") stopped the build with error CS1503: Argument 1: cannot convert from 'string' to 'System.Predicate<string>'Pass a test: names.Find(name => name == "Milo") printed Milo. To ask only whether the item is there, names.Contains("Milo") printed True

FAQ​

How do I get every match, or the last one?​

With FindAll and FindLast. The FindAll reference: Retrieves all the elements that match the conditions defined by the specified predicate. The FindLast reference: Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List<T>. With the same test, pet.Age > 5, FindAll returned a list of 2 pets, Milo and Bella, and FindLast returned Bella.

What does FindIndex return?​

The position of the first match, counted from 0, or -1 when nothing passes. The reference: The zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, -1. That's why it can tell a real 0 in a list of numbers from no match at all.

Is Find the same as LINQ's FirstOrDefault?​

On a list, they gave the same answer: with the test pet.Age > 5, both returned Milo. FirstOrDefault also works on an array, and on an array of the same three pets it returned Milo too.

Conclusion​

Find goes through a List<T> from the first item and returns the first one your test accepts. When nothing passes, you get the type's default value: null for a record or a class, so check for it before you use the result, and 0 for an int, where FindIndex tells a real 0 from no match.

Additional Resources​