在LINQ中分组,总和

moe*_*zed 5 c# linq

假设我有下表:

user type amount
2    a    10
2    b    20
2    c    40
3    a    15
3    b    20
3    c    45
Run Code Online (Sandbox Code Playgroud)

我想用(c - (a + b))用户和类型替换(c)金额,我怎么能这样做?谢谢

Ste*_*ven 4

这是一个方法:

更新(现在使用Sum):

from item in table
group item by item.user into g
let a = (from i in g where i.type == "a" select i.amount).Sum()
let b = (from i in g where i.type == "b" select i.amount).Sum()
let c = (from i in g where i.type == "c" select i.amount).Sum()
select c - (a + b);
Run Code Online (Sandbox Code Playgroud)