Linq分组成均匀分组

时间:2011-05-28 15:21:47

标签: c# linq

我目前正在开展一个项目,其中一个要求是能够通过网络服务向供应商下订单。 一整天,各种人都会在购物袋中添加商品,然后在营业日结束时下订单。

当订单交付后,仓库中的人员会解开物品,并检查匹配的交货单。

为了使这项工作更轻松,他们希望将订单拆分为较小的子订单,每个子订单最多15个。

这是我第一次尝试解决这个问题:

var groupingBySupplierID = shoppingBag.Where(x => x.SelectedSupplier != null).GroupBy(x => x.SelectedSupplier.SupplierID))

var groupedListOf15Items = groupingBySupplierID                        
                        .Select((item, index) => new {item, index}) //Items with the index in the list
                        .GroupBy(x => x.index/15) //Integerdivison on the index.. 1..14/15 == 0. 15..29/15 == 1 and so on
                        .Select(x => x.Select(y => y.item)); //Get the items back out from the groups

但是,如果有17个项目,我会得到一个计数为15的IEnumerable<IEnumerable<ShoppingBagItem>>,然后是一个带有2个项目的1。

理想情况下,我希望获得X列表,每个列表中的项目数量均匀分布,在此示例中为2,计数分别为9和8。

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:3)

在我看来,你应该先在这里做一些数学...找到你需要的组数(div),然后将总数除以此来看每组有多少项。现在在您的分组中使用此值(而不是15):

    int maxItemsPerGroup = 15;
    int totalItems = 17;

    // some math - could probably be cleaner
    int groups = totalItems / maxItemsPerGroup;
    if ((totalItems % maxItemsPerGroup) != 0) groups++;
    int itemsPerGroup = totalItems / groups;
    if ((totalItems % groups) != 0) itemsPerGroup++;

并按itemsPerGroup分组。