Split List into Sublists with LINQ

前端 未结 30 2457
灰色年华
灰色年华 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 06:43

    This is an old question but this is what I ended up with; it enumerates the enumerable only once, but does create lists for each of the partitions. It doesn't suffer from unexpected behavior when ToArray() is called as some of the implementations do:

        public static IEnumerable> Partition(IEnumerable source, int chunkSize)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
    
            if (chunkSize < 1)
            {
                throw new ArgumentException("Invalid chunkSize: " + chunkSize);
            }
    
            using (IEnumerator sourceEnumerator = source.GetEnumerator())
            {
                IList currentChunk = new List();
                while (sourceEnumerator.MoveNext())
                {
                    currentChunk.Add(sourceEnumerator.Current);
                    if (currentChunk.Count == chunkSize)
                    {
                        yield return currentChunk;
                        currentChunk = new List();
                    }
                }
    
                if (currentChunk.Any())
                {
                    yield return currentChunk;
                }
            }
        }
    

提交回复
热议问题