gpt4 book ai didi

c# - Linq 平均分组

转载 作者:行者123 更新时间:2023-11-30 22:38:17 24 4
gpt4 key购买 nike

我目前正在从事一个项目,其中一项要求是能够通过网络服务向供应商下订单。一整天,不同的人将商品添加到购物袋中,然后在工作日结束时下订单。

当订单交付后,仓库人员会打开元素包装,并检查匹配的送货单。

为了简化这项工作,他们希望将订单拆分为更小的子订单,每个子订单最多包含 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 个项目,我会得到一个 IEnumerable<IEnumerable<ShoppingBagItem>>计数为 15,然后 1 有 2 个项目。

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

关于如何实现这一点有什么想法吗?

最佳答案

在我看来,您应该先在这里做一些数学运算...找到您需要的组数 (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 分组。

关于c# - Linq 平均分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6162539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com