Posted By

witmann on 05/18/12


Tagged

list split parts division splitting


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Splitting C# list into equal parts


 / Published in: C#
 

URL: http://stackoverflow.com/questions/3892734/split-c-sharp-collection-into-equal-parts-maintaining-sort

author SomeMiscGuy@StackOverflow

  1. public static List<T>[] Partition<T>(List<T> list, int totalPartitions)
  2. {
  3. if (list == null)
  4. throw new ArgumentNullException("list");
  5.  
  6. if (totalPartitions < 1)
  7. throw new ArgumentOutOfRangeException("totalPartitions");
  8.  
  9. List<T>[] partitions = new List<T>[totalPartitions];
  10.  
  11. int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);
  12. int k = 0;
  13.  
  14. for (int i = 0; i < partitions.Length; i++)
  15. {
  16. partitions[i] = new List<T>();
  17. for (int j = k; j < k + maxSize; j++)
  18. {
  19. if (j >= list.Count)
  20. break;
  21. partitions[i].Add(list[j]);
  22. }
  23. k += maxSize;
  24. }
  25.  
  26. return partitions;
  27. }

Report this snippet  

You need to login to post a comment.