2

我有下表

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

3 回答 3

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)
}
于 2012-10-14T17:09:59.703 回答
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)

(未经测试)

于 2012-10-15T09:22:54.353 回答
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
于 2014-02-04T11:50:40.923 回答