Search code examples
c#methodsyield

How to yield a nested IENumerable?


I know how to yield values in a method with return value IENumerable

public IEnumerable<int> GetDigits()
{
    yield return 1;
    yield return 1;
    yield return 1;
}

but how is the correct Syntax for a nested IEnumerable<IEnumerable<int>>?

public IEnumerable<IEnumerable<int>> GetNestedDigits()
{
    yield return yield return 1; //??
}

Solution

  • You cannot directly nest the yield return statements. You'd have to create another method:

    public IEnumerable<IEnumerable<int>> GetNestedDigits()
    {
        yield return GetNestedEnumerable();
    }
    
    public IEnumerable<int> GetNestedEnumerable()
    {
        yield return 1;
    }