Sequence contains no elements

By FoxLearn 2/28/2025 9:41:17 AM   114
When you call .Single() on an IEnumerable that is empty or contains more than one element, you encounter the following exception:
System.InvalidOperationException: Sequence contains no elements

or

System.InvalidOperationException: Sequence contains more than one element

Here are several ways to handle this issue:

Using .SingleOrDefault() instead of .Single()

When the IEnumerable is empty, .SingleOrDefault() returns the default value for the type. However, if the sequence contains more than one element, it will still throw an exception.

IEnumerable<IProduct> products = GetProducts();  
var product = products.SingleOrDefault();  
Console.WriteLine($"Product = {product == default(IProduct)}");

For reference types, this returns null. For value types, this returns 0 or the equivalent default value for that type.

Using .Any() to check if the IEnumerable is empty

Instead of relying on the default value, you can use .Any() to verify if the IEnumerable contains any elements before calling .Single().

IEnumerable<IProduct> products = GetProducts();  

if (products.Any())  
{  
    var product = products.Single();  
    Console.WriteLine($"Product = {product}");  
}  
else  
{  
    Console.WriteLine("No products found.");  
}

Custom default object with .SingleOrDefault()

You can create an extension method to return a custom default object when the sequence is empty.

static class IEnumerableExtension  
{  
    public static T SingleOrDefault<T>(this IEnumerable<T> list, T defaultObj)  
    {  
        if (!list.Any())  
            return defaultObj;  
        else  
            return list.Single();  
    }  
}

For reference types, you can use the Null Object Pattern (an object that represents a "no-op" or default state).

For example:

IEnumerable<IProduct> products = GetProducts();  
var product = products.SingleOrDefault(new DefaultProduct());

For value types, you can specify a special value that has meaning in your application:

IEnumerable<int> productIds = GetProductIds();  
var productId = productIds.SingleOrDefault(-1);

By using these approaches, you can avoid exceptions and handle empty or invalid sequences gracefully.