分组依据,LINQ中的求和

本文关键字:求和 LINQ | 更新日期: 2023-09-27 18:21:04

假设我有下表:

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)amount,我该怎么做?感谢

分组依据,LINQ中的求和

这里有一种方法:

更新(现在使用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);

我建议对Steven的答案进行扩展,因为这只会返回一系列标量c值,而不会使它们与用户或ab值相关联。试试这个:

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};

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

var query2 = query1.SelectMany(q => new List<TableType>
                                    {
                                        new TableType(q.user, "a", q.a),
                                        new TableType(q.user, "b", q.b),
                                        new TableType(q.user, "c", q.c)
                                    })
                                    .OrderBy(t => t.user)
                                    .ThenBy(t => t.type);

注意:我已经测试过了,它是有效的。