C# - elegant way of partitioning a list?

前端 未结 11 692
情歌与酒
情歌与酒 2020-12-01 04:36

I\'d like to partition a list into a list of lists, by specifying the number of elements in each partition.

For instance, suppose I have the list {1, 2, ... 11}, and

11条回答
  •  攒了一身酷
    2020-12-01 04:57

    Something like (untested air code):

    IEnumerable> PartitionList(IList list, int maxCount)
    {
        List partialList = new List(maxCount);
        foreach(T item in list)
        {
            if (partialList.Count == maxCount)
            {
               yield return partialList;
               partialList = new List(maxCount);
            }
            partialList.Add(item);
        }
        if (partialList.Count > 0) yield return partialList;
    }
    

    This returns an enumeration of lists rather than a list of lists, but you can easily wrap the result in a list:

    IList> listOfLists = new List(PartitionList(list, maxCount));
    

提交回复
热议问题