Single and SingleOrDefault Methods in Linq

Single and SingleOrDefault Methods in Linq

In this article, I am going to discuss the Single and SingleOrDefault Methods in Linq with some examples. Please read our previous article before proceeding to this article, where we discussed the Last and LastOrDefault methods in Linq with some examples.

Single Method in Linq: 

The Linq Single Method is used to returns a single element from a data source or you can say from a sequence. There are two overloaded versions available for this Linq Single Method, which are shown in the below image.

Single and SingleOrDefault Methods in Linq

As you can see, the first overloaded version of the Single method does not take any parameter. This method simply returns the only element from a sequence. If the data source is empty or if the data source contains more than one element, then it throws an exception.

On the other hand, the second overloaded version of the Single method takes one predicate as a parameter and using this predicate you can specify a condition. This method returns the only element from the sequence which satisfied the given condition. In this case, the method will throw an exception when any of the following condition is true.

  1. If the data source is empty.
  2. When the given condition does not satisfy any element in the sequence.
  3. If the given condition satisfies more than one element.
Example1: Linq Single Method

In the below example, we have created the data source which contains only one element. Now when we apply the Single method on this data source then it will return the only element which is present in the data source.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence contains one element
            List<int> numbers = new List<int>() { 10 };
            int number = numbers.Single();
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

Output: 10

Example2: Using Single Method with Empty Data source

In the following example, the data source is empty. When we apply the Single method on an empty data source then it will throw an exception as shown in the below example.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence contains no element
            List<int> numbers = new List<int>() { };
            int number = numbers.Single();
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

Now run the application and you will get the following exception.

Sequence Contains no elements in Linq Single Method

As you can see when we run the application, we will get the above Invalid Operation Exception and it clearly shows the reason that the sequence contains no elements.

Example3:

In the following example, we applied the Single method on a data source that contains more than one element.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sequence contains more than one element
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.Single();
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

When you run the above application you will get the following exception. This is because now the sequence contains more than one element.

Sequence Contains more than one elements in Linq Single Method

Note: If your sequence contains more than one element and you need to fetch a single element based on some condition then you need to use the other overloaded versions of the Single method which takes one predicate as a parameter.

Example4:

In the following example, we use the Single method which takes one predicate as a parameter. Using that predicate we specify our condition which is going to return only one element from the sequence.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.Single(num => num == 20);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

Output: 20

Here we will get the output as expected as the specified condition returns a single element from the sequence.

Example5:

In the following example, the specified condition returns more than one element and hence we will get an exception saying the sequence contains more than one matching element.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.Single(num => num > 10);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

Now run the application and you will get the following exception.

Sequence Contains more than one matching elements

Example6:

In the below example, the specified Single method does not return any data and hence we will get sequence contains no matching element exception.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.Single(num => num < 10);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}

When you run the application you will get the following exception.

Sequence Contains no matching element

Note: If you don’t want to throw an exception when the sequence is empty or if the specified condition does not return an element from a sequence then you need to use the Linq SingleOrDefault method.

SingleOrDefault Method in Linq: 

The Linq SingleOrDefault method is very much similar to the Linq Single method except that this method will not throw an exception when the sequence is empty or when no element in the sequence satisfied the given condition.

Note: The most important point that you need to keep in mind is, like the Single method, the SingleOrDefault method still throws an exception when the sequence contains more than one matching element for the given condition.

There are two overloaded versions available for this method as shown in the below image.

Single and SingleOrDefault Methods in Linq

As you can see the first overloaded version of this method does not take any parameter. It simply returns the only element from the sequence. It the sequence is empty then it returns the default value without throwing an exception.

Using the second overloaded version of this method you can specify a condition. If the specified condition does not return any data then it will not throw an exception instead it returns the default value.

Example7:

In the following example, the specified condition does not match any elements in the sequence. So, in this case, the SingleOrDefault method will return the “0” as “0” is the default value for the integer data type.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.SingleOrDefault(num => num < 10);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}
Example8:

In the following example, the sequence is empty. But as we use the SingleOrDefault method we will not get any exception when we run the below example instead we will get the default value 0.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { };
            int number = numbers.SingleOrDefault(num => num < 10);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}
Example9:

In the following example, we will get an exception. This is because now the sequence contains more than elements for the specified condition.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() {10, 20, 30 };
            int number = numbers.SingleOrDefault(num => num > 10);
            Console.WriteLine(number);
            Console.ReadLine();
        }
    }
}
What is the difference between Single and SingleOrDefault methods in Linq?

Both Single and SingleOrDefault methods in Linq are used to returns a single element from a sequence. But if the sequence is empty or if no element is satisfied with the given condition, then the Single method will throw an exception while the SingleOrDefault method will not throw an exception instead it returns a default value.

In the next article, I am going to discuss the Linq DefaultIfEmpty method in Linq with some examples. In this article, I try to explain the Single and SingleOrDefault method with some examples. I hope you understood the need and use of Single and SingleOrDefault methods.

Leave a Reply

Your email address will not be published. Required fields are marked *