如何使用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);
}
}
}热门推荐
2 甄嬛传祝福语简短
10 收到公公生日祝福语简短
11 弟弟的祝福语简短霸气
12 孩子转学离群祝福语简短
13 送给同桌的祝福语简短
14 简短古文生日祝福语
15 毕业祝福语保安文案简短
16 朋友领证祝福语长文简短
17 高考给舍友祝福语简短
18 良师益友祝福语简短