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: MoreLinqAssembly: 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
)
<ExtensionAttribute>
Public Shared Function SingleOrFallback(Of TSource) (
source As IEnumerable(Of TSource),
fallback As Func(Of TSource)
) As TSource
public:
[ExtensionAttribute]
generic<typename TSource>
static TSource SingleOrFallback(
IEnumerable<TSource>^ source,
Func<TSource>^ fallback
)
[<ExtensionAttribute>]
static member SingleOrFallback :
source : IEnumerable<'TSource> *
fallback : Func<'TSource> -> 'TSource
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:
TSourceThe 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 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