C# - elegant way of partitioning a list?

前端 未结 11 724
情歌与酒
情歌与酒 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:06

    Or in .Net 2.0 you would do this:

        static void Main(string[] args)
        {
            int[] values = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
            List items = new List(SplitArray(values, 4));
        }
    
        static IEnumerable SplitArray(T[] items, int size)
        {
            for (int index = 0; index < items.Length; index += size)
            {
                int remains = Math.Min(size, items.Length-index);
                T[] segment = new T[remains];
                Array.Copy(items, index, segment, 0, remains);
                yield return segment;
            }
        }
    

提交回复
热议问题