C# Sum Object List on specific property

I’m currently developing an ASP.NET app where I need to display several charts based on data I receive from a database. I receive them as a list of objects, which looks like this for example:

    { name: "A", val: 20 }, 
    { name: "A", val: 10 }, 
    { name: "B", val: 6 }, 
    { name: "C", val: 1 }, 
    { name: "C", val: 20 } 

I want to transform this list, the target list should look like this:

{ { name: "A", val: 30 } { name: "B", val: 6 }, { name: "C", val: 21 } }

I want all objects with name “A” to be “merged together” into one object, where val now is the sum of all values of the single objects. Currently I’m using a foor loop and a new List, which I loop through evvery time to achieve this, but I think this is very inefficient. There is probably some LINQ option to do this but I haven’t found anything. How can I optimize this?

Thanks in advance!


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can simply use a GroupBy and project the results

Groups the elements of a sequence.


var results = List.GroupBy(x => x.name)
                  .Select( x => new { name = x.Key, val = x.Sum(x => x.val) });

Method 2

You can use .GroupBy() to group list of object based on Name property and then use .Sum() to calculate sum of all values of Val property.

var groupResult = ListOfObject
    .GroupBy(x => x.Name)
    .Select(y => new
                Name= y.Key,
                Val = y.Sum(s => s.Val)

.Net Fiddle

Method 3

You can also sum it on database side

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x