使用LINQ按多个属性分组和求和
本文关键字:求和 属性 LINQ 使用 | 更新日期: 2023-09-27 18:05:42
我有一个项目集合,如下:
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进行分组,以及从金额和费用(金额+费用)计算的Total
所以使用上面的数据,我想得到这些结果:
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过滤和分组吗?
分组后使用.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)
});
Linus在这个方法上是正确的,但是一些属性是关闭的。看起来' agencycontracd '是你的主键,它与你想要给用户的输出无关。我认为这就是你想要的(假设你改变你的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)
});