![](/img/trans.png)
[英]Linq Task - Group List elements and do action for grouped elements with condition
[英]LINQ - Grouped list with condition
但我想進一步了解
假設一個列表包含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
如何獲得如下結果:(如果count> 10,請轉到下一行)
ITEM |QUANTITY
=================
ITEM01 | 100
ITEM01 | 100
ITEM01 | 10
ITEM01 | 10
ITEM01 | 10
ITEM02 | 50
ITEM02 | 50
謝謝你的幫助!
檢查代碼中的注釋以查看正在發生的情況以及查詢的實際作用。
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.