Split C# collection into equal parts, maintaining sort

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

    As I understand you want to break enumerable on several parts with equal size and without breaking the order of your elements. It looks like the only choice is to get the length of your input enumerable first, so you would need at least two iterations through the enumerable.

    0 讨论(0)
  • 2021-02-19 19:10

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

     private IEnumerable<IEnumerable<T>> SplitMaintainingOrder<T>(IEnumerable<T> 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<IEnumerable<T>>();
                        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<int> recordNumbers = new List<int>() { 1, 2, 3, 4, 5, 6,7,8,9,10,11};
    
    var splitedItems = SplitMaintainingOrder<int>(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..

    0 讨论(0)
提交回复
热议问题