且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在数组中查找重复项并显示重复次数?

更新时间:2022-11-13 22:25:41

由于您无法使用LINQ,因此可以使用集合和循环来实现:

Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}