Back to: LINQ Tutorial For Beginners and Professionals
LINQ Single and SingleOrDefault Methods in C#
In this article, I am going to discuss the LINQ Single and SingleOrDefault Methods in C# with Examples using both Method and Query Syntax. Please read our previous article, where we discussed the LINQ Last and LastOrDefault Methods in C# with Examples.
LINQ Single Method in C#:
The LINQ Single Method is used to return 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.
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. In this case, 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 we 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 conditions is true.
- If the data source is empty.
- When the given condition does not satisfy any element in the sequence.
- If the given condition satisfies more than one element.
Example to Understand LINQ Single Method in C#
Let us see an Example to Understand LINQ Single Method in C# using both Method and Query Syntax. In the below example, we have created one data source which contains only one element. Now when we apply the Single method to 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 LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains one element List<int> numbers = new List<int>() { 10 }; //Fetching the Only Element from the Sequenece using Method Syntax int numberMS = numbers.Single(); //Fetching the Only Element from the Sequenece using Query Syntax int numberQS = (from num in numbers select num).Single(); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
Output: 10
LINQ Single Method with Empty Data source
Let us see what happens when we call the LINQ Single Method on an Empty Data Source. In the following example, the data source is empty. When we apply the LINQ Single method on the empty data source then it will throw System.InvalidOperationException: ‘Sequence contains no elements’ exception.
using System.Linq; using System; using System.Collections.Generic; namespace LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains no element i.e. Empty Data Source List<int> numbers = new List<int>(); //Fetching the Only Element from the Sequenece using Method Syntax int numberMS = numbers.Single(); //Fetching the Only Element from the Sequenece using Query Syntax int numberQS = (from num in numbers select num).Single(); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
Now run the application and you will get the following exception. Here, we are getting the Invalid Operation Exception and it clearly shows the reason that the sequence contains no elements.
What happens when the Sequence Contains more than one element?
If the Sequence contains more than one element and if we apply the Single method on that sequence then we will get System.InvalidOperationException: ‘Sequence contains more than one element’ Exception. In the following example, we applied the Single method to a data source that contains more than one element.
using System.Linq; using System; using System.Collections.Generic; namespace LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains more than one element List<int> numbers = new List<int>() { 10, 20, 30 }; ; //Fetching the Only Element from the Sequenece using Method Syntax int numberMS = numbers.Single(); //Fetching the Only Element from the Sequenece using Query Syntax int numberQS = (from num in numbers select num).Single(); //Printing the Returned element by Single Method Console.WriteLine(numberQS); 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 which is clearly told by the following exception message.
Using the Second Overloaded Version of the Single Method which takes the Predicate as a Parameter:
If the sequence contains more than one element and we need to fetch a single element based on some condition, then we need to use the second overloaded version of the LINQ Single method which takes one predicate as a parameter. Let us understand this with an example. 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. Here, we are returning the element which is equal to 20.
using System.Linq; using System; using System.Collections.Generic; namespace LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains more than one element List<int> numbers = new List<int>() { 10, 20, 30 }; ; //Fetching the Only Element from the Sequenece using Method Syntax //Where the Element is 20 int numberMS = numbers.Single(num => num == 20); //Fetching the Only Element from the Sequenece using Query Syntax //Where the Element is 20 int numberQS = (from num in numbers select num).Single(num => num == 20); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
Output: 20
Here we will get the output as expected as the specified condition returns a single element from the sequence.
What Happens if the Condition Specified in the Single Method Returns more than One Element?
If the Condition Specified in the Single Method Returns more than One Element, then we will get System.InvalidOperationException: ‘Sequence contains more than one matching element’ exception. Let us understand this with an example. In the below 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 LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains more than one element List<int> numbers = new List<int>() { 10, 20, 30 }; ; //Fetching the Only Element from the Sequenece using Method Syntax //Where the Element > 10 int numberMS = numbers.Single(num => num > 10); //Fetching the Only Element from the Sequenece using Query Syntax //Where the Element > 10 int numberQS = (from num in numbers select num).Single(num => num > 10); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
Now run the application and you will get the following exception and clearly tell us that Sequence contains more than one matching element.
What Happens if the Condition Specified in the Single Method does not return any data?
If the Condition Specified in the Single Method does not return any data, then we will get System.InvalidOperationException: ‘Sequence contains no matching element’ exception. Let us understand this with an example. In the below example, the specified condition does not return any data and hence we will get an exception saying the sequence contains no matching elements.
using System.Linq; using System; using System.Collections.Generic; namespace LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains more than one element List<int> numbers = new List<int>() { 10, 20, 30 }; ; //Fetching the Only Element from the Sequenece using Method Syntax //Where the Element < 10 int numberMS = numbers.Single(num => num < 10); //Fetching the Only Element from the Sequenece using Query Syntax //Where the Element < 10 int numberQS = (from num in numbers select num).Single(num => num < 10); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
When you run the application you will get the following exception.
When to use the LINQ SingleOrDefault Method in C#?
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. 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.
This method returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition.
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. Like, the Single Method, there are also two overloaded versions available for this method in LINQ. They are as follows.
As you can see, the first overloaded version of this method does not take any parameters. It simply returns the only element from the sequence. If the sequence is empty then it returns the default value without throwing an exception. If the sequence contains more than one element then it will throw an exception.
Using the second overloaded version of this method we 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. But if the specified condition matches multiple data in the data source, then it will throw an exception.
Example to Understand LINQ SingleOrDefault Method in C#
Let us see an example to understand the LINQ SingleOrDefault method in C# with both Method and Query Syntax. In the following example, the specified condition does not match any elements in the sequence. So, in this case, the SingleOrDefault method will return 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(); } } }
Output: 0
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 LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains no element List<int> numbers = new List<int>(); //Fetching the Only Element from the Sequenece using Method Syntax //Where the Element < 10 int numberMS = numbers.SingleOrDefault(num => num < 10); //Fetching the Only Element from the Sequenece using Query Syntax //Where the Element < 10 int numberQS = (from num in numbers select num).SingleOrDefault(num => num < 10); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
Output: 0
What happens when the specified condition returns more than one element?
If the specified condition matches with more than one element, then we will get an exception. In the following example, we will get an exception. This is because the specified condition matches more than one element.
using System.Linq; using System; using System.Collections.Generic; namespace LINQSingleMethodDemo { class Program { static void Main(string[] args) { //Sequence contains List<int> numbers = new List<int>() { 10, 20, 30 }; //Fetching the Only Element from the Sequenece using Method Syntax //Where the Element > 10 int numberMS = numbers.SingleOrDefault(num => num > 10); //Fetching the Only Element from the Sequenece using Query Syntax //Where the Element > 10 int numberQS = (from num in numbers select num).SingleOrDefault(num => num > 10); //Printing the Returned element by Single Method Console.WriteLine(numberQS); Console.ReadLine(); } } }
When you run the above code, you will get the following exception.
What is the Difference Between LINQ Single and SingleOrDefault Methods in C#?
Both LINQ Single and SingleOrDefault Methods are used to return 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 based on the data type. The similarity between them is that if the specified condition matches with more than one element, then both methods are going to throw Exceptions.
In the next article, I am going to discuss the Linq LINQ DefaultIfEmpty Method in C# with Examples. In this article, I try to explain the LINQ Single and SingleOrDefault Methods in C# with Examples. I hope you understood the need and use of LINQ Single and SingleOrDefault Methods.