Split List into Sublists with LINQ

前端 未结 30 2492
灰色年华
灰色年华 2020-11-21 06:26

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

30条回答
  •  故里飘歌
    2020-11-21 07:03

    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++];
            }
        }
    

提交回复
热议问题