Split C# collection into equal parts, maintaining sort

前端 未结 8 1804
野的像风
野的像风 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 18:49

    This will do exactly as requested. It will also cater for uneven groupings i.e. 27 elements in to 10 groups will yield 7 groups of three and 3 groups of two

            public static IEnumerable> SplitMaintainingOrder(this IEnumerable list, int parts)
        {
            if (list.Count() == 0) return Enumerable.Empty>();
    
            var toreturn = new List>();
    
            var splitFactor = Decimal.Divide((decimal)list.Count(), parts);
            int currentIndex = 0;
    
            for (var i = 0; i < parts; i++)
            {
                var toTake = Convert.ToInt32(
                    i == 0 ? Math.Ceiling(splitFactor) : (
                        (Decimal.Compare(Decimal.Divide(Convert.ToDecimal(currentIndex), Convert.ToDecimal(i)), splitFactor) > 0) ? 
                            Math.Floor(splitFactor) : Math.Ceiling(splitFactor)));
    
                toreturn.Add(list.Skip(currentIndex).Take(toTake));
                currentIndex += toTake;
            }
    
            return toreturn;
        }
    

    For demo purposes

            [TestMethod]
        public void splitlist()
        {
            var list = new decimal[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 };
    
            var splitlists = list.SplitMaintainingOrder(10);
    
            int i = 1;
    
            foreach (var group in splitlists)
            {
                Console.WriteLine("Group {0} elements {1}", i++, String.Join(",", group));                 
            }
        }
    

    the above demo yields

    Test Name:  splitlist
    Test Outcome:   Passed
    Result StandardOutput:  
    Group 1 elements 1,2,3
    Group 2 elements 4,5
    Group 3 elements 6,7,8
    Group 4 elements 9,10,11
    Group 5 elements 12,13
    Group 6 elements 14,15,16
    Group 7 elements 17,18,19
    Group 8 elements 20,21
    Group 9 elements 22,23,24
    Group 10 elements 25,26,27
    

提交回复
热议问题