Splitting C# list into equal parts


/ Published in: C#
Save to your folder(s)

author SomeMiscGuy@StackOverflow


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.