GroupBy和sum to dictionary

时间:2017-06-07 07:50:47

标签: c# linq grouping

我有两张像这样连接在一起的桌子。

var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals 
              t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
             .GroupBy(c => c.Brand)
             .ToDictionary(t => t.Key, t => t.Count());

这几乎给了我想要的东西,它返回不同cFormat行的数量, 但我想在t2.Qty而不是

进行总结

如果数据看起来像这样......

Brand           Qty
Volvo           2
Volvo           1
Tesla           4
Tesla           9

我当前的查询给了我这样的结果..

Volvo           2
Tesla           2

但我希望它是

Volvo           3
Tesla           13

我怎样才能将其改为像那样工作?

2 个答案:

答案 0 :(得分:4)

使用Sum代替Count

.ToDictionary(t => t.Key, t => t.Sum(c => c.Qty));

答案 1 :(得分:3)

只需将Count来电更改为Sum来电,指定要汇总的属性,如下所示:

var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
             t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
            .GroupBy(c => c.Brand)
            .ToDictionary(t => t.Key, t => t.Sum(x => x.Qty));