在数组中查找最常见的元素

时间:2013-10-16 15:21:57

标签: c#

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

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

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

3 个答案:

答案 0 :(得分:19)

使用LINQ尝试这样的事情。

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

答案 1 :(得分:1)

如果您不喜欢使用LINQ或正在使用例如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;
            }
        }            

答案 2 :(得分: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