开发者

Linq grouping into evenly divided groups

开发者 https://www.devze.com 2023-03-09 10:46 出处:网络
Im currently working on a project, where one of the requirements is to be able to place an order at a supplier through a webservice.

Im currently working on a project, where one of the requirements is to be able to place an order at a supplier through a webservice. All through the day, various people will add items to the shoppingbag, and then at the end of the businessday the order will be placed.

When the order is then delivered the guys in the warehouse unpacks the items, and checks the matching delivery note.

In order to make this job easier, they would like the order be split up into smaller suborders, with a maximum of 15 items in each.

This was my first attempt a ttackling that:

var groupingBySu开发者_Go百科pplierID = 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

However if there is, say 17 items, im getting an IEnumerable<IEnumerable<ShoppingBagItem>> with a count of 15, and then 1 with 2 items.

Ideally i would like to get back X lists with an evenly distributed number of items in each, in this example 2 with a count of 9 and 8 respectively.

Any ideas as to how i can achieve this ?


It seems to me you should just do some math here first... Find the number of groups you need (div) and then just divide the total by this to see how many items per group. Now use this value (rather than the 15) in your group-by:

    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++;

and group by itemsPerGroup.

0

精彩评论

暂无评论...
验证码 换一张
取 消