Reputation: 1690
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!
Upvotes: 2
Views: 2355
Reputation: 241
You can also sum it on database side https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php
Upvotes: 1
Reputation: 16049
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)
});
Upvotes: 1
Reputation: 81493
You can simply use a GroupBy
and project the results
Groups the elements of a sequence.
Example
var results = List.GroupBy(x => x.name)
.Select( x => new { name = x.Key, val = x.Sum(x => x.val) });
Upvotes: 2