Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I would like to know how to group item and split every N record by using LINQ

I have this table contains 22 ITEM01 and each quantity is 10, 2 ITEM02 with quantity 50 for each

VB
# |ITEM  |QUANTITY
==================
1 |ITEM01| 10
2 |ITEM01| 10
3 |ITEM01| 10
.     .     .
.     .     .
22|ITEM01| 10
23|ITEM02| 50
24|ITEM02| 50


How to get the expected result below by using LINQ? (Group by item if count >10, if not, let it shows one by one.

VB
ITEM  |QUANTITY
=================
ITEM01 | 100
ITEM01 | 100
ITEM01 | 10
ITEM01 | 10
ITEM01 | 10
ITEM02 | 50
ITEM02 | 50


I've tried following code, but it cannot achieve
C#
var query =
    items.GroupBy(item => item.Name)
         .SelectMany(g => g.Select((item, index) => new { item, index })
                           .GroupBy(x => x.index / 10)
                           .Select(batch => new Item {
                                 Name = batch.First().item.Name,
                                 Quantity = batch.Sum(x => x.item.Quantity)
                            })).OrderBy(item => item.Name);


Thanks for your help
Posted
Updated 24-Jan-14 15:47pm
v2
Comments
BillWoodruff 24-Jan-14 22:43pm    
Off the top of my head: won't you need to use the Linq 'Aggregate function here ?

http://stackoverflow.com/a/7105616/133321

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900