Traditionally, converting a large collection into batches requires a lot of array allocation and copying operations. Using an offset and count sounds like a good alternative, but very few APIs support it.
This is where the
BatchAsSegments extension method comes into play. Rather than returning a new collection, it gives a window into the underlying list. The return type is
ReadOnlyListSegment is a struct with 3 fields, a source list, an offset, and a count. It can be cast into a
IReadonlyList<T>, but that’s not recommended because it requires a boxing operation and the goal of this is to allocation-free.
ReadOnlyListSegment can be done via an
IEnumerator pair as usual, but again that requires allocation. As an alternative, you can perform a for-each loop against it directly using a struct based enumerator. This is inspired by the enumerator on