(C# Language) LINQ - FirstOrDefault, Single, First, SingleOrDefault

In this tutorial we learn about FirstOrDefault, Single, First and SingleOrDefault extension methods available on an IEnumerable. Use FirstOrDefault for finding the first element that matches a condition. It returns the default value if no matching records exist. "First" does the same thing but throws an exception instead. SingleOrDefault returns the default value if exactly one record cannot be found. There is one more called Find which should be used if the search has to be by a primary key value.
(Rev. 07-Nov-2022)

Categories | About |     |  

Parveen,

Table of Contents (top down ↓)

Create a Project

Create a C# console project for the latest version of .NET Core. Open the solution explorer and open the program.cs file. Let us add code to this file.

Since we are learning a tutorial, we can create a list of anonymous types. The dynamic keyword can be used to specialize a list for anonymous types. We have added four items to this list.

Video Explanation (see it happen!)

Please watch the following youtube video:

The FirstOrDefault and First

LINQ provides two methods - FirstOrDefault and First - for querying the first element that satisfies a condition. The condition is expressed with a lambda expression that returns a boolean.

Let us use the FirstOrDefault method to obtain the first item that has its Code = "QCM".

The first matching element will be obtained in the variable called item.



List<dynamic> ls = new() {
                            new{Code = "ACD", Size = 2310 },
                            new{Code = "BRT", Size = 2000 },
                            new{Code = "CED", Size = 500 },
                            new{Code = "QCM", Size = 1030 }
                          };

var item = ls.FirstOrDefault(m => m.Code == "QCM");

// use a null condition ?. safety guard 
// because firstordefault can return null 
Console.WriteLine ( $"{item?.ToString()}" );

// throws an exception if an item 
// not found 
// var item2 = ls.First(m => m.Code == "GHI"); 

// Console.WriteLine($"{item2?.ToString()}"); 

The console writeline method displays the item using ToString method.

Notice that we have written item?.ToString instead of item.ToString because the FirstOrDefault method returns the default value if there is no matching candidate. The default value of a reference type is null, so the null-conditional operator (?.) has been used as a safety guard. The ?. operator prevents member access if null is returned.


// output 

{ Code = QCM, Size = 1030 }

We can run the program to verify that the first matching record is printed.

Next let's come to First. This method differs from FirstOrDefault in only one respect - it throws an exception if a matching element cannot be found. It doesn't return a null or default value. It throws an exception that must be caught with a try-catch guard.

We can now use First to query for an element that doesn't exist. In this case there will be a runtime exception.

We can run the project to verify that the program crashes with an exception.

The SingleOrDefault and Single

SingleOrDefault and Single are two more similar looking functions. They return an element only if there is exactly one match.

SingleOrDefault returns the default value if there is no matching record, or if there are multiple matching records. The Single function, however, throws an exception under these conditions.

This is about Single, SingleOrDefault, First and FirstOrDefault - thankyou!


This Blog Post/Article "(C# Language) LINQ - FirstOrDefault, Single, First, SingleOrDefault" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.