C#程序查找数组是否包含重复项
设置一个数组-
int[] arr = {
89,
12,
56,
89,
};现在,创建一个新字典-
var d = new Dictionary < int, int > ();
使用dictionary方法ContainsKey(),在数组中找到重复的元素-
foreach(var res in arr) {
if (d.ContainsKey(res))
d[res]++;
else
d[res] = 1;
}这是完整的代码-
示例
using System;
using System.Collections.Generic;
namespace Demo {
public class Program {
public static void Main(string[] args) {
int[] arr = {
89,
12,
56,
89,
};
var d = new Dictionary < int, int > ();
foreach(var res in arr) {
if (d.ContainsKey(res))
d[res]++;
else
d[res] = 1;
}
foreach(var val in d)
Console.WriteLine("{0} occurred {1} times", val.Key, val.Value);
}
}
}输出结果
89 occurred 2 times 12 occurred 1 times 56 occurred 1 times
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬