我有这两个类:
class ZoneInformation : Scores
{
public string Zone {get;set;}
}
class Scores
{
public string TypeQ {get;set;}
public int High {get;set;}
public int Low {get;set;}
}
我制作了一个这样的集合:区域和每个区域中的 3 种不同类型:
Collection<ZoneInformation> Values = new Collection<ZoneInformation>();
Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone1", High=5, Low=6});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone1", High=7, Low=8});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone1", High=9, Low=10});
Values.Add(new ZoneInformation{TypeQ="Type1", Zone="Zone2", High=11, Low=12});
Values.Add(new ZoneInformation{TypeQ="Type2", Zone="Zone2", High=13, Low=14});
Values.Add(new ZoneInformation{TypeQ="Type3", Zone="Zone2", High=15, Low=16});
如何按所有区域“分组”我的“值”集合中的元素?像这样
new Scores{TypeQ="Type1", High=16, Low=18});
可以看到High=5+11,两个'Type1'之和
最佳答案
这对于 Linq 来说非常简单:
var groups = Values.GroupBy(zi => zi.TypeQ)
.Select(g => new Scores
{
TypeQ = g.Key,
High = g.Sum(zi=> zi.High),
Low = g.Sum(zi=> zi.Low)
}
);
关于c# - 按值(value)分组收藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435477/