0

I have a method that returns a list of MyClass. Within that method I split a list of MyClass into smaller chunks of let´s say 500 elements. Now I wonder if this is possible together with a yield-statement. Currently I have this code. However I´m curious if there is a way to yield return the whole bunch without this messy second inner loop.

IEnumerable<MyClass> DoSomething() 
{
    List<MyClass> myList = ...
    foreach(var chunk in myList.Chunk(500))  // split the list in smaller lists
    {
        foreach(MyClass m in chunk) yield return m;
    }
}

Of course this works, but I wonder if I can also use the yield to return the whole bunch deferredly.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

1 Answers1

0

Assuming that Chunk returns some sort of List<> you could do:

IEnumerable<IList<MyClass>> DoSomething() 
{
    List<MyClass> myList = ...
    foreach(var chunk in myList.Chunk(500))  // split the list in smaller lists
    {
        yield return chunk;
    }
}
Sean
  • 60,939
  • 11
  • 97
  • 136