C#在Dictionary中重复键错误< int>键入键 [英] C# Duplicate key error in Dictionary with List<int> type key

查看:161
本文介绍了C#在Dictionary中重复键错误< int>键入键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在尝试创建一个字典项,其键为列表类型,值为自定义对象类型。它给了我一个错误

已经添加了一个具有相同键的项目。


这是我的代码:

展开 | 选择 | Wrap | 行号

解决方案

您是否从代码中发现您只创建了一个列表?


创建一个List意味着什么? ...如果你在列表中说一个项目,那么代码很好,因为它稍后在代码中对我有用


详细说明,你只是创建一个list对象:PKey。然后尝试在循环的每次迭代中将相同的对象(PKey)添加到字典对象A的Keys集合中。


添加到A'的密钥集合中的每个对象必须是唯一的。


要修复代码,你需要将列表声明移到循环内部

展开 | 选择 | Wrap | 行号< /跨度>

Hello,
I am trying to create a dictionary item with its key as list type and value as custom object type. It gives me a error
"An item with the same key has already been added."

Here is my code:

Expand|Select|Wrap|Line Numbers

解决方案

You do realize from your code that you have created only one list?


Creating one List means? ... if you are saying about 1 item in the list, then the code is fine as it is of some use to me later in the code


To elaborate, you are only creating one list object: PKey. You then try to add that same object (PKey) to the Keys collection of your dictionary object A on each iteration of the loop.

Each object added to A''s keys collection must be unique.

To fix your code you''d need to move the list declaration to inside the loop

Expand|Select|Wrap|Line Numbers


这篇关于C#在Dictionary中重复键错误&lt; int&gt;键入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆