如何显示数组中重复的所有值

本文关键字:数组 何显示 显示 | 更新日期: 2023-09-27 18:23:56

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

如何显示数组中重复的所有值

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<Int32>,其值为 36

如果你想得到计数值及其值,看看乔恩的答案。

像这样:

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也是一种可能性。但它很慢(无论如何,性能不应该是一个决定因素(。

如果你想得到像{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();

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

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

要像Seminda的例子一样获得输出,只需省略最终的.区别((。

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());

KeyValuePair s 的值是计数。