选择多个字段分组并求和 [英] Select multiple fields group by and sum
问题描述
我想用linq(对象列表)进行查询,但我真的不知道该怎么做,我可以进行分组和求和,但不能选择其余字段. 示例:
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. Example:
ID Value Name Category
1 5 Name1 Category1
1 7 Name1 Category1
2 1 Name2 Category2
3 6 Name3 Category3
3 2 Name3 Category3
我想按ID分组,按值求和,并返回所有类似的字段.
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
推荐答案
已更新:
如果要避免对所有字段进行分组,则可以仅按Id
进行分组:
Updated :
If you're trying to avoid grouping for all the fields, you can group just by Id
:
data.GroupBy(d => d.Id)
.Select(
g => new
{
Key = g.Key,
Value = g.Sum(s => s.Value),
Name = g.First().Name,
Category = g.First().Category
});
但是此代码假定对于每个Id
,都应用相同的Name
和Category
.如果是这样,您应该考虑按照@Aron的建议进行规范化.这意味着将Id
和Value
保留在一个类中,并将Name
,Category
(以及对于相同的Id
而言,其他任何字段都相同)移至另一类,同时还具有Id
以供参考.规范化过程减少了数据冗余和依赖性.
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.
这篇关于选择多个字段分组并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!