未处理的异常.System.Collections.Generic.KeyNotFoundException:尝试增加值



这是代码片段,我正试图找出数组中的重复数字。

public static void Main(string[] args)
{
var map = new Dictionary<int, int>();
int[] nums = new int[]{ 1,3,4,2,2};
for(int i = 0; i < nums.Length; i++)
{
map[nums[i]]+=1;
if(map[nums[i]] > 1)
{
Console.WriteLine(map[nums[i]]);
break;
}
}
}

答案是您需要使用字典的其他功能

if (map.ContainsKey(key))
{
int current = map[key];
map[key] = current + 1;
}
else
map.Add(key, 1);

这将带你去哪里

最新更新