I'm learning DotNet. I can easy generate iterator over iterators on Python, but what is the canonical way to do it in C#? I create function Slices
(not tested, may have bugs) but what looks dangerous for me is creation of segments (with new
): if input sequence is very big then a lot of new segments will be created. I do it because: 1) segment allow to keep size of slice - it can be cutted in the last slice 2) I don't know is it possible to yield enumerators.
Alternative way may be to create only one segment and to reinitialize it on each iteration, but ArraySegment
seems not supports such thing (so, may be custom struct is needed for segment).
public static IEnumerable<ArraySegment<T>> Slices<T>(IEnumerable<T> sequence, int sliceSize) {
T[] slice = new T[sliceSize];
IEnumerator<T> items = sequence.GetEnumerator();
int from = 0, to;
while (true) {
for (to = from; to < from + sliceSize && items.MoveNext(); to++) {
slice[from - to] = items.Current;
}
from = to;
yield return new ArraySegment<T>(slice, from, to - from);
}
}
So, what is the right or/and canonical way to generate iterator of iterators in C# (needed in slices, groups, etc)