var prizeGroup = prizeDetailCollection
.GroupBy(m => m.UserId, (key, c) => new {
Key = key,
C1 = c.Sum(n => n.Currency_1),
C2 = c.Sum(n => n.Currency_2) + c.Sum(n => n.Currency_10)
})
.ToList();
prizeGroup.ForEach(delegate(var item) { // CS0815: 無法將匿名方法轉換為 System.Action<...>
if (item.C1 > 0m) { }
if (item.C2 > 0m) { }
});
`List
// 方案 1:Lambda 表達式(推薦,類型推導自動)
prizeGroup.ForEach(item => {
if (item.C1 > 0m) { /* ... */ }
if (item.C2 > 0m) { /* ... */ }
});
// 方案 2:顯式指定類型的匿名方法
prizeGroup.ForEach(delegate(AnonymousType item) { ... }); // 匿名類型無法命名,不可行
// 方案 3:foreach 語句(最通用、可讀性最好)
foreach (var item in prizeGroup) {
if (item.C1 > 0m) { }
if (item.C2 > 0m) { }
}
// 使用 record 定義分組結果類型(C# 9+)
public record PrizeGroupResult(Guid Key, decimal C1, decimal C2);
// 查詢投影為強類型
var prizeGroup = prizeDetailCollection
.GroupBy(m => m.UserId)
.Select(g => new PrizeGroupResult(
g.Key,
g.Sum(n => n.Currency_1),
g.Sum(n => n.Currency_2) + g.Sum(n => n.Currency_10)
))
.ToList();
foreach (var item in prizeGroup) { /* 業務邏輯 */ }