用来查找数组中是否包含重复元素的 C# 程序
设置数组 −
int[] arr = {
89,
12,
56,
89,
};现在,创建新的字典 −
var d = new Dictionary < int, int > ();
使用字典方法 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP