Is there any way I can separate a List
into several separate lists of SomeObject
, using the item index as the delimiter of each s
If the source collection implements IList < T > (random access by index) we could use the below approach. It only fetches the elements when they are really accessed, so this is particularly useful for lazily-evaluated collections. Similar to unbounded IEnumerable< T >, but for IList< T >.
public static IEnumerable> Chunkify(this IList src, int chunkSize)
{
if (src == null) throw new ArgumentNullException(nameof(src));
if (chunkSize < 1) throw new ArgumentOutOfRangeException(nameof(chunkSize), $"must be > 0, got {chunkSize}");
for(var ci = 0; ci <= src.Count/chunkSize; ci++){
yield return Window(src, ci*chunkSize, Math.Min((ci+1)*chunkSize, src.Count)-1);
}
}
private static IEnumerable Window(IList src, int startIdx, int endIdx)
{
Console.WriteLine($"window {startIdx} - {endIdx}");
while(startIdx <= endIdx){
yield return src[startIdx++];
}
}