There are several instances of IEnumerable<T> and I want to first get the first of each, then the second of each, and so on.
If they were lists, I'd do it like this:
List<List<T>> myLists = ...;
bool iLessThanMaxSize = true;
for (int i=0; iLessThanMaxSize; i++)
{
iLessThanMaxSize = false;
for (int j=0; j<myLists.Count; j++)
{
if (i < myLists[j].Count)
{
iLessThanMaxSize = true;
yield return myLists[j][i];
}
}
}
However, they are not lists, but IEnumerables, which is essential, because the items are computed on demand in a heavy calculation, so computing all of the items at once would take longer than getting only a limited number on demand.
How can I get the same behavior, but working with IEnumerable<T> instead of List<T>?
Edit: By simultaneously, I did not mean multi-threading but just the pattern of enumeration, which is getting the first of each collection, and then the second of each, as opposed to first enumerating through the first collection and then through the second collection and so on (which would be concatenating the IEnumerables). Sorry for the confusion.
Edit: In my specific use case, the enumeration of the collections shall continue until all the elements of all collections are enumerated. In case that the element counts differ, collections that already have been entirely enumerated shall be skipped.
If you want to do more complex things with IEnumerables you often need to get the enumerator and use
.MoveNext()and.Currentto do things.For example:
I would recommend avoiding code like this for large amounts of data. When the amount of data grows you often want to use lower level, less abstract code to help ensure adequate performance.