Enumerable.Empty<TResult> Method

Definition

Returns an empty IEnumerable<T> that has the specified type argument.

C#
public static System.Collections.Generic.IEnumerable<TResult> Empty<TResult>();

Type Parameters

TResult

The type to assign to the type parameter of the returned generic IEnumerable<T>.

Returns

IEnumerable<TResult>

An empty IEnumerable<T> whose type argument is TResult.

Examples

The following code example demonstrates how to use Empty<TResult>() to generate an empty IEnumerable<T>.

C#
IEnumerable<decimal> empty = Enumerable.Empty<decimal>();

The following code example demonstrates a possible application of the Empty<TResult>() method. The Aggregate method is applied to a collection of string arrays. The elements of each array in the collection are added to the resulting IEnumerable<T> only if that array contains four or more elements. Empty is used to generate the seed value for Aggregate because if no array in the collection has four or more elements, only the empty sequence is returned.

C#
string[] names1 = { "Hartono, Tommy" };
string[] names2 = { "Adams, Terry", "Andersen, Henriette Thaulow",
                      "Hedlund, Magnus", "Ito, Shu" };
string[] names3 = { "Solanki, Ajay", "Hoeing, Helge",
                      "Andersen, Henriette Thaulow",
                      "Potra, Cristina", "Iallo, Lucio" };

List<string[]> namesList =
    new List<string[]> { names1, names2, names3 };

// Only include arrays that have four or more elements
IEnumerable<string> allNames =
    namesList.Aggregate(Enumerable.Empty<string>(),
    (current, next) => next.Length > 3 ? current.Union(next) : current);

foreach (string name in allNames)
{
    Console.WriteLine(name);
}

/*
 This code produces the following output:

 Adams, Terry
 Andersen, Henriette Thaulow
 Hedlund, Magnus
 Ito, Shu
 Solanki, Ajay
 Hoeing, Helge
 Potra, Cristina
 Iallo, Lucio
*/

Remarks

The Empty<TResult>() method caches an empty sequence of type TResult. When the object it returns is enumerated, it yields no elements.

In some cases, this method is useful for passing an empty sequence to a user-defined method that takes an IEnumerable<T>. It can also be used to generate a neutral element for methods such as Union. See the Example section for an example of this use of Empty<TResult>().

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0