C# - elegant way of partitioning a list?

前端 未结 11 726
情歌与酒
情歌与酒 2020-12-01 04:36

I\'d like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and

11条回答
  •  心在旅途
    2020-12-01 05:02

    To avoid grouping, mathematics and reiteration.

    The method avoids unnecessary calculations, comparisons and allocations. Parameter validation is included.

    Here is a working demonstration on fiddle.

    public static IEnumerable> Partition(
        this IEnumerable source,
        int size)
    {
        if (size < 2)
        {
            throw new ArgumentOutOfRangeException(
                nameof(size),
                size,
                "Must be greater or equal to 2.");  
        }
    
        T[] partition;
        int count;
    
        using (var e = source.GetEnumerator())
        {
            if (e.MoveNext())
            {
                partition = new T[size];
                partition[0] = e.Current;
                count = 1;
            }
            else
            {
                yield break;    
            }
    
            while(e.MoveNext())
            {
                partition[count] = e.Current;
                count++;
    
                if (count == size)
                {
                    yield return partition;
                    count = 0;
                    partition = new T[size];
                }
            }
        }
    
        if (count > 0)
        {
            Array.Resize(ref partition, count);
            yield return partition;
        }
    }
    

提交回复
热议问题