按值对集合进行分组
本文关键字:集合 | 更新日期: 2023-09-27 18:35:46
我有两个类:
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)
}
);
其他人
说了什么,或者用另一种语法:
var res = from q in Values
group q by q.TypeQ into x
select new Scores()
{
TypeQ = x.Key,
High = x.Sum( y => y.High ),
Low = x.Sum( y => y.Low ),
};