假设我们有这个类:
public enum KindOfPerson
{
Student, Teacher, ...
}
public class Person
{
// This contains only numbers between 0 and 1
public double ScorePercent { get; set; }
public KindOfPerson Type { get; set; }
}
我正在尝试通过KindOfPerson对列表进行分类,但我也想知道同一KindOfPerson的所有人的ScorePercent的平均值。
List<List<Person>> groupedLists = peopleList.GroupBy(person => person.Type)
.OrderBy(group => group.Key)
.Select(group => group.ToList())
.ToList();
答案 0 :(得分:2)
你想用LINQ吗?
您可以使用GroupBy
和Average
方法。
var groupedLists = peopleList.GroupBy(person => person.Type)
.OrderBy(group => group.Key)
.Select(group => new {
People = group.ToList(),
AverageScore = group.Average(p => p.ScorePercent)
})
.ToList();
假设您想要一个Tuple<KindOfPerson, double>
列表,请转到:
var scores = peopleList.GroupBy(p => p.Type)
.Select(g => Tuple.Create(g.Key, g.Average(p => p.ScorePercent)))
.ToList();
创建Dictionary<KindOfPerson, double>
非常相似:
var scores = peopleList.GroupBy(p => p.Type)
.ToDictionary(g => g.Key, g => g.Average(p => p.ScorePercent));