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
热门推荐
7 修祖屋祝福语简短
10 对疫情的简短祝福语
11 祝妹妹毕业祝福语简短
12 农民朋友发财祝福语简短
13 弟弟生日祝福语简短的话
14 合字的祝福语简短
15 药店祝福语简短10字
16 新郎表白成语祝福语简短
17 美好的成语祝福语简短
18 舅妈生日红包祝福语简短