使用linq分组和求和 [英] group by and sum using linq

查看:71
本文介绍了使用linq分组和求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Id | Value

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

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

I would like to calculate using linq query the total for every id. I know I have to use the group by statement as same in sql:

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

但是如何使用linq或lambda实现呢?

but how can I achieve this using linq or lambda?

推荐答案

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

这篇关于使用linq分组和求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆