当其他2个列值相同时,LINQ求和一些列

时间:2012-10-14 17:03:46

标签: vb.net linq sum

我有下表

+-------+--------+----------+
| 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 |
+-------+--------+----------+

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

Artur Udod的答案很好(并且有额外的功能),但简单的LINQ答案是:

Dim result = From row In YourTable
             Group By row.catid, row.name Into Group
             Select catid, name, quantity = Sum(From g In group Select g.quantity)

(未测试的)

答案 2 :(得分:0)

就我而言,马克的答案以这种形式取得了成功:

Dim result = From row In YourTable
         Group By row.catid, row.name Into Group
         Select catid, name, quantity = (From g In group Select g.quantity).Sum