Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split C# collection into equal parts, maintaining sort

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 them incorrectly. Basically, if I was to look at the items in the collection, the order should be the same when compared to the broken up collections joined. Here is the code I am using that doesn't work:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
            int i = 0;
            var splits = from name in list
                         group name by i++ % parts into part
                         select part.AsEnumerable();
            return splits;
        }
  • int parts = number of sub enumerables
like image 820
Brian David Berman Avatar asked Oct 08 '10 17:10

Brian David Berman


1 Answers

Jon Skeet's MoreLINQ library might do the trick for you:

https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs

var items = list.Batch(parts);  // gives you IEnumerable<IEnumerable<T>>
var items = list.Batch(parts, seq => seq.ToList()); // gives you IEnumerable<List<T>>
// etc...

Another example:

public class Program
{
    static void Main(string[] args)
    {
        var list = new List<int>();
        for (int i = 1; i < 10000; i++)
        {
            list.Add(i);
        }

        var batched = list.Batch(681);

        // will print 15. The 15th element has 465 items...
        Console.WriteLine(batched.Count().ToString());  
        Console.WriteLine(batched.ElementAt(14).Count().ToString());
        Console.WriteLine();
        Console.WriteLine("Press enter to exit.");
        Console.ReadLine();
    }
}

When I scanned the contents of the batches, the ordering was preserved.

like image 134
code4life Avatar answered Sep 20 '22 12:09

code4life