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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With