gpt4 book ai didi

vb.net - 当其他 2 个列值相同时,LINQ 对某些列求和

转载 作者:行者123 更新时间:2023-12-02 05:27:18 26 4
gpt4 key购买 nike

我有下表

+-------+--------+----------+
| catid | name | quantity |
+-------+--------+----------+
| 1 | table | 10 |
| 2 | chair | 5 |
| 2 | chair | 10 |
| 1 | table | 10 |
| 2 | chair | 15 |
| 3 | pencil | 20 |
+-------+--------+----------+

使用 LINQ 我想对具有相同名称 catid 的行求和并将其保存到相同的数据表中

所以结果就是这张表

+-------+--------+----------+
| catid | name | quantity |
+-------+--------+----------+
| 1 | table | 20 |
| 2 | chair | 30 |
| 3 | pencil | 20 |
+-------+--------+----------+

最佳答案

var result = (from row in YourTable
group row by new {row.catid, row.name}
into grp
select new
{
grp.Key.catid,
grp.Key.name,
Quantity = grp.Sum(row => row.Quantity)
}).ToList();

编辑:刚刚注意到它带有 VB 标记。对不起。嗯,应该是这样的:

Dim result = From row In YourTable
Group By Key = New With {row.catid, row.name} Into Group
Select New With
{
.Catid = Key.catid,
.Name = Key.Name,
.Quantity = Group.Sum(Function(x) x.quantity)
}

关于vb.net - 当其他 2 个列值相同时,LINQ 对某些列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com