SingleOrDefault and FirstOrDefault Methods in LINQ to SQL

The SingleOrDefault() method returns a single specific element of a sequence or default value if that element is not found in the sequence. Whenever you use SingleOrDefault, you clearly state that the query should result in at most a single result.

The FirstOrDefault() method returns a first specific element of a sequence or default value if that element is not found in the sequence. Whenever FirstOrDefault is used, the query can return any amount of results but you state that you only want the first one.

I create a console application to explain the differences between these methods.

Adding a LINQ to SQL Class

Entity classes are created and stored in LINQ to SQL Classes files (.dbml files). The O/R Designer opens when you open a .dbml file. It is a DataContext class that contains methods and properties for connecting to a database and manipulating the data in the database. The DataContext name corresponds to the name that you provided for the .dbml file

Step 1: Right-click on the project in the Solution Explorer then go to "Add" and click on "Class.."

Step 2: Choose "LINQ to SQL Classes" from the list and give the name "User" for the dbml name. After that click on "Add".

Step 3: Drag the User table from the database in the Server Explorer and drop onto the O/R Designer surface of the "User.dbml" file.

Linq1.jpg

Figure 1.1: Table in User.dbml file

We will look at various scenario for FirstOrDefault and SingleOrDefault methods. So let's see each one by one.

If sequence returns 0 elements

If a sequence returns 0 elements then the FirstOrDefault method sets the default value for the type. Suppose we are retrieving a specific record from the database table and that specific record does not exist in the database table then the sequence contains 0 elements and the FirstOrDefault method sets a null value for that object.

In the following code snippet the sequence does not contain an element then the FirstOrDefault method sets a null value for the object type and the catch block executes. We define NullReferenceException as a parameter in the catch block that represents that this catch block executes when a null value is set for an object and data is being retrieved from that object.

using System;

using System.Linq;

namespace FirstOrSingle

{

    class Program

    {

        static void Main(string[] args)

        {

            using (UserDataContext dataContext = new UserDataContext())

            {

                var users = from user in dataContext.Users

                            where user.Id==5

                           select user;

                var firstUser = users.FirstOrDefault();               

                try

                {

                    Console.WriteLine("Name : {0} Age : {1}", firstUser.Name, firstUser.Age);

                   

                }

                catch(NullReferenceException ex)

                {                   

                    Console.WriteLine("No Record Found");

                    Console.Write(ex.Message);

                  

                }

                Console.ReadKey();

            }

        }

    }

 

}

After running the application, we get the result that represents that the catch block executes due to retrieving a value from the object that has a null value.

Linq2.jpg

Figure 1.2 Output of program when sequence contains one element

We can implement the SingleOrDefault method on the same sequence that does not contain any elements; it then also sets a null value to the object.
 

using System;

using System.Linq;

namespace FirstOrSingle

{

    class Program

    {

        static void Main(string[] args)

        {

            using (UserDataContext dataContext = new UserDataContext())

            {

                var users = from user in dataContext.Users

                            where user.Id==5

                           select user;

                var singleUser = users.SingleOrDefault();               

                try

                {

                    Console.WriteLine("Name : {0} Age : {1}", singleUser.Name, singleUser.Age);

                   

                }

                catch(NullReferenceException ex)

                {                   

                    Console.WriteLine("No Record Found");

                    Console.Write(ex.Message);

                  

                }

                Console.ReadKey();

            }

        }

    }

 

}

We get the same result as in Figure 1.1 that represents that there is not a difference between the FirstOrDefault and SingleOrDefault methods when the sequence does not contain any elements.

If sequence contains 1 element

If the sequence contains only 1 element then there is no difference between the FirstOrDefault and SingleOrDefault methods, both will return the same one element. For example:
 

using System;

using System.Linq;

 

namespace FirstOrSingle

{

    class Program

    {

        static void Main(string[] args)

        {

            using (UserDataContext dataContext = new UserDataContext())

            {

                var users = from user in dataContext.Users

                            where user.Id==4

                           select user;

                var firstUser = users.FirstOrDefault();               

                var singleUser = users.SingleOrDefault();               

                try

                {

                    Console.WriteLine("Result By FirstOrDefault Method");

                    Console.WriteLine("Name : {0} Age : {1}", firstUser.Name, firstUser.Age);

                    Console.WriteLine("======================================================");

                    Console.WriteLine("Result By SingleOrDefault Method");

                    Console.WriteLine("Name : {0} Age : {1}", singleUser.Name, singleUser.Age);

                   

                }

                catch(NullReferenceException ex)

                {                  

                  

                    Console.Write(ex.Message);

                  

                }

                Console.ReadKey();

            }

        }

    }

 

}


After running the application we get the result that represents the same result for both methods.

Linq3.jpg

Figure 1.3 Output of Program when sequence contains one element

If the sequence contains many elements

If the sequence contains many elements then the FirstOrDefault method returns only one element that is on top in the sequence. The following code snippet shows that the top one element is gotten from this sequence using the FirstOrDefault method.
 

using System;

using System.Linq;

 

namespace FirstOrSingle

{

    class Program

    {

        static void Main(string[] args)

        {

            using (UserDataContext dataContext = new UserDataContext())

            {

                var users = from user in dataContext.Users                           

                           select user;

               

                try

                {

                    var firstUser = users.FirstOrDefault();

                    Console.WriteLine("Name : {0} Age : {1}", firstUser.Name, firstUser.Age);               

                   

                }

                catch(InvalidOperationException ex)

                {                   

                    Console.Write(ex.Message);                  

                }

                Console.ReadKey();

            }

        }

    }

 

}


After running the application, we get the top first element from the sequence.

Linq4.jpg

Figure 1.4 one element from the sequence when the sequence contains more than one

When the sequence contains many elements and uses the SingleOrDefault method to get an element then we get an exception that represents that sequence containing more than one element. See the following code snippet.
 

using System;

using System.Linq;

 

namespace FirstOrSingle

{

    class Program

    {

        static void Main(string[] args)

        {

            using (UserDataContext dataContext = new UserDataContext())

            {

                var users = from user in dataContext.Users                           

                           select user;

               

                try

                {

                    var singleUser = users.SingleOrDefault();

                    Console.WriteLine("Name : {0} Age : {1}", singleUser.Name, singleUser.Age);               

                   

                }

                catch(InvalidOperationException ex)

                {                  

                    Console.Write(ex.Message);                  

                }

                Console.ReadKey();

            }

        }

    }

 

}


After running the application we get the result that shows an exception which was created by the SingleOrDefault method due to the sequence that contains more than one element.

Linq5.jpg

Figure 1.5 Exception when sequence contains more than one element

Conclusion

If you want an exception to be thrown if the sequence contains more than one element then use SingleOrDefault. If you always want one record no matter what the sequence contains, use FirstOrDefault.

 

Up Next
    Ebook Download
    View all
    Learn
    View all