FallbackIfEmptyExtensionFallbackIfEmptyT(IEnumerableT, T) Method

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

Definition

Namespace: MoreLinq.Extensions
Assembly: MoreLinq (in MoreLinq.dll) Version: 3.4.0+b99a6a8cc504caf2d48372fe54a2f8116c59cd0c
C#
public static IEnumerable<T> FallbackIfEmpty<T>(
	this IEnumerable<T> source,
	T fallback
)

Parameters

source  IEnumerableT
The source sequence.
fallback  T
The value to return in a singleton collection if source is empty.

Type Parameters

T
The type of the elements in the sequences.

Return Value

IEnumerableT
An IEnumerableT that contains fallback if source is empty; otherwise, source.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerableT. 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).

Example

C#
var numbers = new[] { 123, 456, 789 };
var result = numbers.Where(x => x == 100).FallbackIfEmpty(-1).Single();
The result variable will contain -1.

See Also