【问题标题】:Find most common element in array查找数组中最常见的元素
【发布时间】:2013-10-16 15:21:57
【问题描述】:

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

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

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

【问题讨论】:

  • 不应该是string[] aPOS = new string[]{"11","11","18","18","11","11"};

标签: c#


【解决方案1】:

使用 LINQ 尝试类似的操作。

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

【讨论】:

    【解决方案2】:

    如果您不喜欢使用 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;
                }
            }            
    

    【讨论】:

      【解决方案3】:

      您可以使用 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-03
        相关资源
        最近更新 更多