使用linq分组和总和

时间:2017-01-25 08:01:24

标签: c# asp.net linq

Id | Value

1    50
2    60
3    80
3    50
2    20
1    60
1   100

我想用linq查询计算每个id的总数。我知道我必须在sql中使用group by语句:

select id, sum(Value)
from MyTable
group by id

但是如何使用linq或lambda来实现这个目标?

3 个答案:

答案 0 :(得分:4)

var list;
// manipulate list from your table;

list
  .GroupBy(t=>t.Id)
  .Select(t=>new { ID= t.Key , Value= t.Sum(u=>u.Value)}).ToList

答案 1 :(得分:1)

没有测试,但应该有效:

from entry in MyTable
group entry by entry.Id into g
select new { Id = g.Key, Sum = g.Sum(e => e.Value) };

或者,如果您更喜欢方法链语法:

MyTable.GroupBy(entry => entry.Id).Select(g => new { Id = g.Key, Sum = g.Sum(e => e.Value) });

答案 2 :(得分:0)

你可以试试这个

var results = from p in tables
              group by p.Id into g
              select new { Id = g.Key, Value = g.Sum(item=>item.Value) };
相关问题