如何使用C#检查数组是否包含重复数字?
首先,设置一个数组-
int[] arr = {
87,
55,
23,
87,
45,
23,
98
};现在声明一个字典并遍历数组,并获取所有元素的计数。您从字典中获得的值显示数字的出现-
foreach(var count in arr) {
if (dict.ContainsKey(count))
dict[count]++;
else
dict[count] = 1;
}让我们看完整的例子-
示例
using System;
using System.Collections.Generic;
namespace Demo {
public class Program {
public static void Main(string[] args) {
int[] arr = {
87,
55,
23,
87,
45,
23,
98
};
var dict = new Dictionary < int, int > ();
foreach(var count in arr) {
if (dict.ContainsKey(count))
dict[count]++;
else
dict[count] = 1;
}
foreach(var val in dict)
Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
}
}
}热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短