SuperJMN
SuperJMN

Reputation: 13972

More compact way for "yield return"?

I have this method that yields the values yielded by 2 methods:

private IEnumerable<Node> ParseEmptyElement()
{
    foreach (var node in ParseMembersOfObject()) 
    {
        yield return node;
    }

    foreach (var node in ParseNestedProperty()) 
    {
        yield return node;
    }
}

It seems very verbose for me.

Is there a better way express "yield all values from MethodX" and after that, do the same for MethodY?

Example:

private IEnumerable<Node> ParseEmptyElement()
{
    #yield all# items from ParseMembersOfObject();    
    #yield all# items from ParseNestedProperty();
}

I don't want to be force to write the foreach loops into a single line! but I also don't want to write fully-fledged foreach loops with curly braces and all the stuff :)

Upvotes: 2

Views: 133

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

As Marc commented, this is equivalent:

private IEnumerable<Node> ParseEmptyElement()
{
    return ParseMembersOfObject().Concat(ParseNestedProperty());
}

Concat is implemented using deferred execution, so this will not evaluate your enumerables early.

Incidentally, Concat is implemented with the foreach loops on a single line:

static IEnumerable<TSource> ConcatIterator<TSource>(IEnumerable<TSource> first, 
                                                    IEnumerable<TSource> second) {
    foreach (TSource element in first) yield return element;
    foreach (TSource element in second) yield return element;
}

If you don't like Concat, and you still want braces, you could still keep them and just format your code more concisely:

private IEnumerable<Node> ParseEmptyElement()
{
    foreach (var node in ParseMembersOfObject()) { yield return node; }
    foreach (var node in ParseNestedProperty())  { yield return node; }
}

Upvotes: 2

Related Questions