Split C# collection into equal parts, maintaining sort

前端 未结 8 1780
野的像风
野的像风 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:10

    To split a generic list in to equal chunks use below generic method

     private IEnumerable> SplitMaintainingOrder(IEnumerable list, int columnCount)
                    {
                        var elementsCount = list.Count();
                        int rowCount = elementsCount / columnCount;
                        int noOfCells = elementsCount % columnCount;
    
                        int finalRowCount = rowCount;
                        if (noOfCells > 0)
                        {
                            finalRowCount++;
                        }
    
                        var toreturn = new List>();
                        var pushto = 0;
                        for (int j = 0; j < columnCount; j++)
                        {
                            var start = j;
                            int i = 0;
                            var end = i;
                            for (i = 0; i < finalRowCount; i++)
                            {
                                if ((i < rowCount) || ((i == rowCount) && (j < noOfCells)))
                                {
                                    start = j;
                                    end = i;
                                }
                            }
                            toreturn.Add(list.Skip(pushto).Take(end + 1));
                            pushto += end + 1;
                        }
    
                        return toreturn;
    
                    }

    List recordNumbers = new List() { 1, 2, 3, 4, 5, 6,7,8,9,10,11};
    
    var splitedItems = SplitMaintainingOrder(recordNumbers , 4);

    Output will be:
    
    List 1 : 1,2,3
    List 2 : 4,5,6
    List 3 : 7,8,9
    List 4 : 10,11

    ~Happy coding..

提交回复
热议问题