2016-04-20 34 views
1

查找模型中最常见的财产我有一个模块类:使用迭代的方法和LINQ

public class Student 
{ 
    public string Name { get; set; } 
    public string Major { get; set; } 
    public int Age { get; set; } 
} 


public string GetPrimaryMajor(List<Student> students) 
{ 
    ... 
} 

我怎样才能实现该方法GetPrimaryMajor()使用迭代来确定students参数最常发生的Major和LINQ的方法?

回答

5

因为这显然是家庭作业,我会给你简单/容易的一个,你可以从那里找出迭代​​的方法。

// Iterate students 
// Track count of each major 
// Keep track of most commonly occurring major by comparing count of 
// currently iterated value vs current most commonly occurring value count 
// Return most commonly occurred major at end of loop. 
2

一种迭代的方法使用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一个。然后通过字典进行基本迭代以找到具有最高值的键。