c# - LINQ 中的分组、求和

标签 c# linq

假设我有下表:

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

我想将 (c) 数量替换为 (c - (a+b)) 按用户和类型分组,我该怎么做?谢谢

最佳答案

这里有一个方法:

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

关于c# - LINQ 中的分组、求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972935/

相关文章:

c# - 如何将数据读取器值从 DAL 传递到表示层

c# - 类方法返回 `this`是不好的做法吗?

c# - 如何使用 linq to xml 从 xml 中获取数据

c# - 节点的内部文本忽略子节点的内部文本

c# - 使用 c# 将纯文本(标题)导出到 excel

c# - 我如何调用 SQLitePCL.Batteries.Init()。?

c# - 将 XML 绑定(bind)到组合框

mysql - Linq-查询主体必须以 C# 中的 select 子句或 group 子句结尾

c# - 使用 Linq/C# 选择随机图像?

c# - 在 C# 函数中生成 Linq 查询