Split List into Sublists with LINQ

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

    Just putting in my two cents. If you wanted to "bucket" the list (visualize left to right), you could do the following:

     public static List> Buckets(this List source, int numberOfBuckets)
        {
            List> result = new List>();
            for (int i = 0; i < numberOfBuckets; i++)
            {
                result.Add(new List());
            }
    
            int count = 0;
            while (count < source.Count())
            {
                var mod = count % numberOfBuckets;
                result[mod].Add(source[count]);
                count++;
            }
            return result;
        }
    

提交回复
热议问题