Split List into Sublists with LINQ

前端 未结 30 2488
灰色年华
灰色年华 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:59

    I wrote a Clump extension method several years ago. Works great, and is the fastest implementation here. :P

    /// 
    /// Clumps items into same size lots.
    /// 
    /// 
    /// The source list of items.
    /// The maximum size of the clumps to make.
    /// A list of list of items, where each list of items is no bigger than the size given.
    public static IEnumerable> Clump(this IEnumerable source, int size)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (size < 1)
            throw new ArgumentOutOfRangeException("size", "size must be greater than 0");
    
        return ClumpIterator(source, size);
    }
    
    private static IEnumerable> ClumpIterator(IEnumerable source, int size)
    {
        Debug.Assert(source != null, "source is null.");
    
        T[] items = new T[size];
        int count = 0;
        foreach (var item in source)
        {
            items[count] = item;
            count++;
    
            if (count == size)
            {
                yield return items;
                items = new T[size];
                count = 0;
            }
        }
        if (count > 0)
        {
            if (count == size)
                yield return items;
            else
            {
                T[] tempItems = new T[count];
                Array.Copy(items, tempItems, count);
                yield return tempItems;
            }
        }
    }
    

提交回复
热议问题