Split C# collection into equal parts, maintaining sort

前端 未结 8 2341
野的像风
野的像风 2021-02-19 18:31

I am trying to split a collection into multiple collections while maintaining a sort I have on the collection. I have tried using the following extension method, but it breaks

8条回答
  •  轮回少年
    2021-02-19 18:58

    I had to make use of this to compare a list of objects to one another in groups of 4... it will keep the objects in the order that the original possessed. Could be expanded to do something other than 'List'

    /// 
    /// Partition a list of elements into a smaller group of elements
    /// 
    /// 
    /// 
    /// 
    /// 
    public static List[] Partition(List list, int totalPartitions)
    {
        if (list == null)
            throw new ArgumentNullException("list");
    
        if (totalPartitions < 1)
            throw new ArgumentOutOfRangeException("totalPartitions");
    
        List[] partitions = new List[totalPartitions];
    
        int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);
        int k = 0;
    
        for (int i = 0; i < partitions.Length; i++)
        {
            partitions[i] = new List();
            for (int j = k; j < k + maxSize; j++)
            {
                if (j >= list.Count)
                    break;
                partitions[i].Add(list[j]);
            }
            k += maxSize;
        }
    
        return partitions;
    }
    

提交回复
热议问题