【问题标题】:How to show all values that repeat in an array.如何显示在数组中重复的所有值。
【发布时间】:2014-11-17 05:59:28
【问题描述】:

我真的希望你能帮我解决这个问题:我目前正在使用 Windows 窗体,我需要在 MessageBox 或 Label 中显示所有在数组中重复的值。例如,如果我的数组存储以下数字:{3, 5, 3, 6, 6, 6, 7} 我需要能够阅读并抓住并展示那些重复的内容,在这种情况下,这将是 3 两次和 6 三次......感谢您的时间!

【问题讨论】:

    标签: c# arrays forms show repeat


    【解决方案1】:
    var array = new int[] { 3, 5, 3, 6, 6, 6, 7 };
    Dictionary<int, int> counts = array.GroupBy(x => x)
                                      .Where(g => g.Count() > 1)
                                      .ToDictionary(g => g.Key, g => g.Count());
    

    KeyValuePairs 的值是计数。

    【讨论】:

      【解决方案2】:

      代码的“核心”逻辑可能如下所示:

           var array = new [] { 3, 5, 3, 6, 6, 6, 7 };
           var duplicates = array.Where(number => array.Count(entry => entry == number) > 1).Distinct();
      

      要获得像 Seminda 示例中那样的输出,只需省略最后的 .Distinct()。

      【讨论】:

        【解决方案3】:

        如果您想获得像 {3,3,6,6,6} 这样的结果输出,请这样做

        int[] my = new int[] { 3, 5, 3, 6, 6, 6, 7 };
                //List<int> lst = my.OfType<int>().ToList();
                var query = my.GroupBy(x => x)
                  .Where(g => g.Count() > 1)
                  .SelectMany(m=>m)
                  .ToList();
        

        【讨论】:

          【解决方案4】:

          类似:

          var numbers = new int[]{3, 5, 3, 6, 6, 6, 7};
          var counterDic = new Dictionary<int,int>();
              foreach(var num in numbers)
              {
                  if (!counterDic.ContainsKey(num))
          {
                      counterDic[num] = 1;
          }
          else 
          {
                  counterDic[num] ++;
          }
              }
          

          正如其他人提到的那样,Linq 也是一种可能性。但它很慢(无论如何,性能不应该是决定因素)。

          【讨论】:

            【解决方案5】:

            LINQ 会有所帮助;

            var array = new int[] { 3, 5, 3, 6, 6, 6, 7 };
            var counts = array.GroupBy(n => n) // Group by the elements based their values.
                              .Where(g => g.Count() > 1) // Get's only groups that have value more than one
                              .Select(k => k.Key) // Get this key values
                              .ToList();
            

            计数为List&lt;Int32&gt;,其值为36

            如果您还想获取计数值及其值,请查看Jon's answer

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-10-18
              • 1970-01-01
              • 1970-01-01
              • 2012-10-25
              • 1970-01-01
              • 2013-05-12
              相关资源
              最近更新 更多