2016-04-20 14 views
1

を使用して、モデルの最も一般的なプロパティを検索し、私持っている以下のモデルクラス:私は、繰り返し使用してstudentsパラメータの中で最も一般的に発生するMajorを決定する方法GetPrimaryMajor()を実装するにはどうすればよい反復アプローチと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) 
{ 
    ... 
} 

とLINQのアプローチ?

答えて

5

これは明らかに宿題なので、簡単で簡単な方法を教えてくれるので、ここから反復的なアプローチを見つけ出すことができます。反復アプローチについて

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

一電位単純に次の擬似コードを考える、反復(潜在的に乏しいパフォーマンス)アルゴリズム:

// 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を用いて反復アプローチ。それを説明するコメントがたくさんあります。

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を使用して、学生が主要なことを持って1ずつ値intを増やすことで、辞書を取り込みます。次に、辞書を通じた基本的な繰り返しを実行して、最も高い値を持つキーを見つけます。