使用LINQ按多个属性进行分组并求和

时间:2013-03-24 23:36:32

标签: c# asp.net asp.net-mvc linq

我有一系列项目,现在是:

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,VendorID和StateID对这些项目进行分组,并根据金额和费用(金额+费用)计算总计

因此,使用上述数据,我希望得到以下结果:

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

这就是我现在所拥有的,它只是获取数据库中的每一行:

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过滤和分组?

2 个答案:

答案 0 :(得分:51)

分组后使用.Select()

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)
                   });

答案 1 :(得分:16)

Linus在这个方法中很受欢迎,但是一些房产已经关闭。看起来'AgencyContractId'是您的主键,它与您想要给用户的输出无关。我认为这就是你想要的(假设你改变你的ViewModel以匹配你在视图中想要的数据)。

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });