0

Read How to use Linq to group every N number of rows already

But i would like to know further

Suppose a list contains 22 ITEM01 with quantity 10 for each, and 2 ITEM02 with quantity 50 for each

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

How to get the result like : (If count > 10, go to next row)

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

Thanks for your help!

Community
  • 1
  • 1
Wayne_Wall
  • 99
  • 3
  • 8

1 Answers1

0

Check comments within code to see what's going on and what the query really does.

// input generation
var input = Enumerable.Range(1, 22)
                      .Select(x => new { ID = x, Item = "ITEM01", Quantity = 10 })
                      .Concat(Enumerable.Range(23, 2)
                                        .Select(x => new { ID = x, Item = "ITEM02", Quantity = 50 }));

// query you're asking for
var output =
    input.GroupBy(x => x.Item) // group by Item first
         .Select(g => g.Select((v, i) => new { v, i }) // select indexes within group
                       .GroupBy(x => x.i / 10)  // group items from group by index / 10
                       .Select(g2 => g2.Select(x => x.v))  // skip the indexes as we don't need them anymore
                       .SelectMany(g2 =>  // flatten second grouping results and apply Sum logic
                           g2.Count() == 10  
                               // if there are 10 items in group return only one item with Quantity sum
                           ? new[] { new { Item = g.Key, Quantity = g2.Sum(x => x.Quantity) } }
                               // if less than 10 items in group return the items as they are
                           : g2.Select(x => new { Item = g.Key, Quantity = x.Quantity })))
          .SelectMany(g => g);  // flatten all results
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263