Split C# collection into equal parts, maintaining sort

前端 未结 8 1834
野的像风
野的像风 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 19:06

    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>
    var items = list.Batch(parts, seq => seq.ToList()); // gives you IEnumerable>
    // etc...
    

    Another example:

    public class Program
    {
        static void Main(string[] args)
        {
            var list = new List();
            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.

提交回复
热议问题