2013-10-16 45 views
3

我有一个字符串数组,它可以包含1个或多个具有各种字符串值的元素。我需要找到数组中最常见的字符串。查找数组中最常见的元素

string aPOS[] = new string[]{"11","11","18","18","11","11"}; 

在这种情况下,我需要返回"11"

+3

不应该是'string [] aPOS = new string [] {“11”,“11”,“18”,“18 ”, “11”, “11”};' – Mayank

回答

18

尝试使用LINQ这样的东西。

int mode = aPOS.GroupBy(v => v) 
      .OrderByDescending(g => g.Count()) 
      .First() 
      .Key; 
0

你可以用LINQ做到这一点,以下是未经测试,但它应该把你在正确的轨道上

var results = aPOS.GroupBy(v=>v) // group the array by value 
        .Select(g => new { // for each group select the value (key) and the number of items into an anonymous object 
            Key = g.Key, 
            Count = g.Count() 
            }) 
         .OrderByDescending(o=>o.Count); // order the results by count 

// results contains the enumerable [{Key = "11", Count = 4}, {Key="18", Count=2}] 

下面是官方Group By documentation

1

如果你不喜欢使用LINQ或正在使用例如.Net 2.0没有LINQ,可以使用foreach循环

string[] aPOS = new string[] { "11", "11", "18", "18", "11", "11"}; 
     var count = new Dictionary<string, int>(); 
     foreach (string value in aPOS) 
     { 
      if (count.ContainsKey(value)) 
      { 
       count[value]++; 
      } 
      else 
      { 
       count.Add(value, 1); 
      } 
     } 
     string mostCommonString = String.Empty; 
     int highestCount = 0; 
     foreach (KeyValuePair<string, int> pair in count) 
     { 
      if (pair.Value > highestCount) 
      { 
       mostCommonString = pair.Key; 
       highestCount = pair.Value; 
      } 
     }