已添加具有相同键的项目。 [英] An item with the same key has already been added.
问题描述
var result = from d in data
select new Dictionary<string, string>()
{
{ "Name", (string)d.Attribute("Name") },
{ "MappedName", (string)d.Attribute("MappedName") },
{ "DataType", (string)d.Attribute("DataType") },
{ "length", (string)d.Attribute("length") }
};
foreach (var item in result)
{
foreach (var y in item)
{
hash.Add(y.Key, y.Value);
}
}
得到错误:具有相同的项目密钥已被添加。
我的xml doc:
getting error as :An item with the same key has already been added.
my xml doc:
<ColumnNames>
<Column Name="RequestDate" MappedName="@A" DataType="Datetime" length="" />
<Column Name="AgentNumber" MappedName="@B" DataType="varchar" length="4" />
</ColumnNames>
推荐答案
此处引发异常line:
The exception is thrown in this line:
hash.Add(y.Key, y.Value);
if y.Key
是已存在于Hashtable的(唯一)Key集合中的值,它当然会抛出该异常。
您有责任确保插入一个独特的值或重新考虑您的应用规范(例如,使用允许重复的其他数据结构等)
祝你好运,
Edo
if y.Key
is a value already existing in the (unique) Key collection of your Hashtable, it will of course throw that exception.
It is your duty to make sure that you insert a value which is unique OR reconsider you application specification, (e.g. using other data structures that allow duplicates etc)
Good luck,
Edo
错误只是意味着因为你的词典都是这样的:
The error simply means that because your dictionaries all look like this:
{ "Name", (string)d.Attribute("Name") },
{ "MappedName", (string)d.Attribute("MappedName") },
{ "DataType", (string)d.Attribute("DataType") },
{ "length", (string)d.Attribute("length") }
当您将它们添加到哈希表时,它尝试使用的键是:
名称,MappedName,数据类型,长度
一旦它在结果集中添加了第一个字典,那么那些键然后存在所以当它试图添加下一个时它会出错,因为它不能再添加带有这些键的条目。
我建议采用某种动态方法来生成密钥他们每次都是独一无二的。
When you adding them to the hashtable the keys it tries to use are:
Name, MappedName, DataType, Length
Once it has added the first dictionary in the results set, those keys then exist so when it tries to add the next one it errors because it cannot add an entry with those keys again.
I would suggest some sort of dynamic approach to key generation to that they are unique each time.
这篇关于已添加具有相同键的项目。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!