[c#] Using LINQ to group by multiple properties and sum

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?

This question is related to c# asp.net asp.net-mvc linq

The answer is


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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to linq

Async await in linq select How to resolve Value cannot be null. Parameter name: source in linq? What does Include() do in LINQ? Selecting multiple columns with linq query and lambda expression System.Collections.Generic.List does not contain a definition for 'Select' lambda expression join multiple tables with select and where clause LINQ select one field from list of DTO objects to array The model backing the 'ApplicationDbContext' context has changed since the database was created Check if two lists are equal Why is this error, 'Sequence contains no elements', happening?