C# SingleOrDefault

1

What does the SingleOrDefault method return in the C# language and the System.Linq namespace? With SingleOrDefault, you either receive the single matching element, or the default value if no element is found.

Example

Note

This program allocates an array of three integers. Next, the SingleOrDefault method is called; a Predicate is specified to search for a single element equal to 5. No such element exists, so the default value of int is returned: 0. Next, SingleOrDefault is called to find an element of value 1; one such element exists. Finally, SingleOrDefault is used to find an element >= 1. Because three elements match this condition, an exception is thrown.

Lambda Expression

This C# example program uses the SingleOrDefault extension method. It requires System.Linq.

Program that uses SingleOrDefault method [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 2, 3 };

	// Default is returned if no element found.
	int a = array.SingleOrDefault(element => element == 5);
	Console.WriteLine(a);

	// Value is returned if one is found.
	int b = array.SingleOrDefault(element => element == 1);
	Console.WriteLine(b);

	try
	{
	    // Exception is thrown if more than one is found.
	    int c = array.SingleOrDefault(element => element >= 1);
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex.GetType());
	}
    }
}

Output

0
1
System.InvalidOperationException

Single versus SingleOrDefault

Question and answer

What is the difference between Single and SingleOrDefault? The only difference is what happens when zero matching elements are found. With Single, an exception is thrown in this case; with SingleOrDefault, the default value is returned. For ints, the default value is 0.

Single Method Default

Summary

The SingleOrDefault method provides a way to ensure zero or one elements exist matching a condition. As with Single, it can be used with no parameters to match all elements. Unfortunately, its behavior on multiple matches, which results in an exception, can lead to confusing code.

LINQ Examples
.NET