如何对实体框架中的列求和 [英] how to sum a column in entity framework

查看:68
本文介绍了如何对实体框架中的列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图汇总一列并明智地获取成员详细信息

I am trying to sum a column and get details member wise

我的表格数据是

id   membername     cost
1   a               100
2   aa              100
3   a               100
4   aa                0
5   b               100






在Entity Framework中,我尝试对费用列求和并得到这样的结果


In Entity Framework I try to sum cost column and get result like this

membername             totalcost
a                      200
aa                     100
b                      100

然后我正在这样做

var result = from o in db.pruchasemasters.Where(d => d.memberid == d.membertable.id && d.entrydate >= thisMonthStart && d.entrydate <= thisMonthEnd)
                     group o by new { o.membertable.members } into purchasegroup
                     select new
                     {
                         membername = purchasegroup.Key,
                         total = purchasegroup.Sum(s => s.price)
                     };

我如何读取结果,我的代码是否正确?

How do I read the results and is my code right or not?

推荐答案

类似的方法会起作用

    var result = db.pruchasemasters.GroupBy(o => o.membername)
                   .Select(g => new { membername = g.Key, total = g.Sum(i => i.cost) });

    foreach (var group in result)
    {
        Console.WriteLine("Membername = {0} Totalcost={1}", group.membername, group.total);
    }

这篇关于如何对实体框架中的列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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