一种迭代的方法使用Dictionary
:
public string GetPrimaryMajor(List<Student> students)
{
var mostCommonMajor = students
.GroupBy(m => m.Major)
.OrderByDescending(gp => gp.Count())
.FirstOrDefault()? // null-conditional operator
.Select(s => s.Major)
.FirstOrDefault();
return mostCommonMajor;
}
对于迭代方法,考虑以下的伪代码作为一个潜在的简单,迭代(潜在效果不佳的)算法。很多评论来解释它进入内部。
后半部分可能特别低效,使用LINQ找到最大值肯定容易得多。但@DavidL已经提供了一个很好的LINQ答案,所以我认为我会留下来说,不要使用任何LINQ。
public string GetPrimaryMajor(List<Student> students)
{
//Create a dictionary of string and int. These are our major names and and the count of students in thaat major respectively
Dictionary<string, int> MajorCounts = new Dictionary<string, int>();
//Iterate through all students
foreach (Student stu in students)
{
//Check if we have already found a student with that major
if (MajorCounts.ContainsKey(stu.Major))
{
//If yes add one to the count of students with that major
MajorCounts[stu.Major]++;
}
else
{
//If no create a key for that major, start at one to count the student we just found
MajorCounts.Add(stu.Major, 1);
}
}
//Now that we have our majors and number of students in each major we need to find the highest one
//Our first one starts as our highest found
string HighestMajor = MajorCounts.First().Key;
//iterate through all the majors
for (int i = 0; i < MajorCounts.Count(); i++)
{
//If we find a major with higher student count, replace our current highest major
if (MajorCounts.ElementAt(i).Value > MajorCounts[HighestMajor])
{
HighestMajor = MajorCounts.ElementAt(i).Key;
}
}
//Return the highet major
return HighestMajor;
}
基本上填充字典由每个学生都有重大的一次使用Major
作为一个字符串键,增加值int
一个。然后通过字典进行基本迭代以找到具有最高值的键。