由多个属性和款项使用LINQ to组 [英] Using LINQ to group by multiple properties and sum

查看:117
本文介绍了由多个属性和款项使用LINQ to组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有项目的集合,在这里它是:

I have a collection of items, here it is:

AgencyID VendorID StateID Amount Fee
1        1        1       20.00  5.00
1        1        1       10.00  2.00
1        1        1       30.00  8.00    
2        2        1       20.00  5.00
2        2        1       5.00   5.00
1        1        2       20.00  5.00
2        2        2       20.00  5.00
2        2        2       40.00  9.00
1        2        2       35.00  6.00
1        2        2       12.00  3.00

我想这些项目进行分组基础上AgencyID,厂商ID和STATEID,以及从总金额和费用计算(金额+手续费)

I'd like these items to be grouped based on the AgencyID, VendorID, and StateID, and the Total calculated from Amount and Fee (Amount + Fee)

所以,使用上面的数据,我想有以下结果:

So using the data above, I'd like to have these results:

AgencyID VendorID StateID Total
1        1        1       75.00    
2        2        1       35.00
1        1        2       25.00
2        2        2       74.00
1        2        2       56.00

下面是我的一切,现在,刚刚得到的每一行中的数据库:

Here's all I have right now, which just gets every row in the database:

var agencyContracts = _agencyContractsRepository.AgencyContracts.
    Select(ac => new AgencyContractViewModel
    {
        AgencyContractId = ac.AgencyContractID,
        AgencyId = ac.AgencyID,
        VendorId = ac.VendorID,
        RegionId = ac.RegionID,
        Amount = ac.Amount,
        Fee = ac.Fee
    });

有谁知道我如何与LINQ过滤和组呢?

Does anyone know how I can filter and group this with LINQ?

推荐答案

使用。选择()分组后:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

这篇关于由多个属性和款项使用LINQ to组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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