c0rd
c0rd

Reputation: 1419

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; //??
}

Upvotes: 4

Views: 2051

Answers (3)

Licht
Licht

Reputation: 1109

If I take all your text literally you can do this using:

IEnumerable<IEnumerable<int>> GetNestedDigits()//{1, 2, 3}, {1, 2, 3}, {1, 2, 3}
{
  yield return new int[] { 1, 2, 3 };
  yield return new int[] { 1, 2, 3 };
}

You have to declare some sort of collection that implements IEnumerable and return that. You can't directly nest yields. Maybe a closer way would be to declare private IEnumerables which you then return.

IEnumerable<int> GetNestedDigitsA()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

IEnumerable<int> GetNestedDigitsB()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

IEnumerable<IEnumerable<int>> GetNestedDigits()//{1, 2, 3}, {1, 2, 3}
{
  yield return GetNestedDigitsA();
  yield return GetNestedDigitsB();
}

Upvotes: 0

Kenneth
Kenneth

Reputation: 28737

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

Upvotes: 6

Jakub Jankowski
Jakub Jankowski

Reputation: 731

Something like this

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

Upvotes: 0

Related Questions