LINQ - 带条件的分组列表

时间:2014-01-25 07:03:18

标签: c# linq group-by

已阅读How to use Linq to group every N number of rows

但我想进一步了解

假设一个清单包含22个ITEM01,每个数量为10,而2个ITEM02,每个数量为50

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

如何获得如下结果:(如果计数> 10,转到下一行)

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

检查代码中的注释,看看发生了什么以及查询真正起作用。

// 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