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
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
});
Does anyone know how I can filter and group this with LINQ?
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
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)
});
Use the .Select()
after grouping:
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)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With