将列表中的元素分类为具有平均值的另一个分类

时间:2011-08-08 18:30:42

标签: c# oop

假设我们有这个类:

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();

1 个答案:

答案 0 :(得分:2)

你想用LINQ吗? 您可以使用GroupByAverage方法。

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));