user192332
user192332

Reputation:

Empty Sequence in LINQ

I recently faced an interview question related to LINQ.

What is the use of empty sequence?.He asked "if i suppose to ask you to use the one,where do you fit it?"

     public static IEnumerable<TResult> Empty<TResult>()
     {
        yield break;
     }

I did not answer it.Help is appreciated.

Upvotes: 9

Views: 3407

Answers (2)

Drew Marsh
Drew Marsh

Reputation: 33379

If you had a loop that aggregated together different sets into a result set you can use it to initialize your result set variable and loop/accumulate. For example:

IEnumerable<string> results = Enumerable.Empty<string>();

for(....)
{
    IEnumerable<string> subset = GetSomeSubset(...);

    results = results.Union(subset);
}

Without Empty you'd have to have written a null check into your loop logic:

IEnumerable<string> results = null;

for(....)
{
    IEnumerable<string> subset = GetSomeSubset(...);

    if(results == null)
    {
        results = subset;
    }
    else
    {
        results = results.Union(subset);
    }
}

It doesn't just have to be a loop scenario and it doesn't have to be Union (could be any aggregate function), but that's one of the more common examples.

Upvotes: 4

Stan R.
Stan R.

Reputation: 16065

You can use this when you want to quickly create an IEnumerable<T> this way you don't have to create a reference to a new List<T> and take advantage of the yield keyword.

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);

Note the use of Union because it is not a List you can not call Add method, but you could call Union on an IEnumerable

Upvotes: 3

Related Questions