在LINQ中分组,总和

时间:2012-01-23 14:10:40

标签: c# linq

假设我有下表:

user type amount
2    a    10
2    b    20
2    c    40
3    a    15
3    b    20
3    c    45

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

我建议对 Steven 的答案进行扩展,因为这只会返回一系列标量c值,而不是让它们与用户或{{1}相关联}和a金额。试试这个:

b

然后,如果您想将其转换回表格形式:

var query1 = from i in table
             group i by i.user
             into g
             let a = g.Where(t => t.type == "a").Sum(t => t.amount)
             let b = g.Where(t => t.type == "b").Sum(t => t.amount)
             let c = g.Where(t => t.type == "c").Sum(t => t.amount)
                   - (a + b)
             select new {user = g.Key, a, b, c};

注意:我已经测试了这个并且它有效。