user2112420 user2112420 - 10 months ago 87
ASP.NET (C#) Question

Select multiple fields group by and sum

I want to do a query with linq (list of objects) and I really don't know how to do it, I can do the group and the sum but can't select rest of the fields.

ID Value Name Category
1 5 Name1 Category1
1 7 Name1 Category1
2 1 Name2 Category2
3 6 Name3 Category3
3 2 Name3 Category3

I want to group by ID, SUM by Value and return all fields like this.

ID Value Name Category
1 12 Name1 Category1
2 1 Name2 Category2
3 8 Name3 Category3

Answer Source

Updated : If you're trying to avoid grouping for all the fields, you can group just by Id:

data.GroupBy(d => d.Id)
        g => new
            Key = g.Key,
            Value = g.Sum(s => s.Value),
            Name = g.First().Name,
            Category = g.First().Category 

But this code assumes that for each Id, the same Name and Category apply. If so, you should consider normalizing as @Aron suggests. It would imply keeping Id and Value in one class and moving Name, Category (and whichever other fields would be the same for the same Id) to another class, while also having the Id for reference. The normalization process reduces data redundancy and dependency.