Click or drag to resize
MoreEnumerableSingleOrFallbackTSource Method
Returns the single element in the given sequence, or the result of executing a fallback delegate if the sequence is empty. This method throws an exception if there is more than one element in the sequence.

Namespace: MoreLinq
Assembly: MoreLinq (in MoreLinq.dll) Version: 1.4.18916.0 (1.4.18916.839)
Syntax
public static TSource SingleOrFallback<TSource>(
	this IEnumerable<TSource> source,
	Func<TSource> fallback
)

Parameters

source
Type: System.Collections.GenericIEnumerableTSource
The source sequence
fallback
Type: SystemFuncTSource
The fallback delegate to execute if the sequence is empty

Type Parameters

TSource
Element type of sequence

Return Value

Type: TSource
The single element in the sequence, or the result of calling the fallback delegate if the sequence is empty.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerableTSource. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).
Exceptions
ExceptionCondition
ArgumentNullExceptionsource or fallback is null
InvalidOperationExceptionThe sequence has more than one element
Remarks
The fallback delegate is not executed if the sequence is non-empty. This operator uses immediate execution and has optimizations for IListT sources.
Examples
var numbers = { 123, 456, 789 };
var result = numbers.Where(x => x == 100).SingleOrFallback(() => -1);
The result variable will contain -1.
See Also