参数异常"具有相同密钥的项目已添加"

时间:2014-10-22 20:48:01

标签: c# exception dictionary

我使用以下代码时出现错误:

Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();

foreach (string line in rct3Lines) 
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    rct3Features.Add(items[0], items[1]);

    ////To print out the dictionary (to see if it works)
    //foreach (KeyValuePair<string, string> item in rct3Features)
    //{
    //    Console.WriteLine(item.Key + " " + item.Value);
    //}

}

错误引发ArgumentException说,

  

“已添加具有相同键的项目。”

我不确定Google搜索后如何解决这个问题。

稍后在代码中我需要访问比较函数的字典:

Compare4To3(rct4Features, rct3Features);

public static void Compare4To3(Dictionary<string, string> dictionaryOne, Dictionary<string, string> dictionaryTwo)
{
    //foreach (string item in dictionaryOne)
    //{

    //To print out the dictionary (to see if it works)
    foreach (KeyValuePair<string, string> item in dictionaryOne)
    {
        Console.WriteLine(item.Key + " " + item.Value);
    }

        //if (dictionaryTwo.ContainsKey(dictionaryOne.Keys)
        //{
        //    Console.Write("True");
        //}
        //else
        //{
        //    Console.Write("False");
        //}
    //}
}

此功能尚未完成,但我正在尝试解决此异常。有什么方法可以解决这个异常错误,并保持对字典的访问以便与此函数一起使用?谢谢

6 个答案:

答案 0 :(得分:31)

此错误相当不言自明。字典键是唯一的,您不能有多个相同的键。要解决此问题,您应该像这样修改代码:

Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();

foreach (string line in rct3Lines) 
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        rct3Features.Add(items[0], items[1]);
    }

    ////To print out the dictionary (to see if it works)
    //foreach (KeyValuePair<string, string> item in rct3Features)
    //{
    //    Console.WriteLine(item.Key + " " + item.Value);
    //}
}

这个简单的if语句确保您只在Key(items[0])尚未出现时才尝试向Dictionary添加新条目。

答案 1 :(得分:8)

正如其他人所说,你不止一次地添加相同的密钥。如果这不是一个有效的方案,那么检查Jdinklage Morgoone的答案(只保存为密钥找到的第一个值),或者,考虑这个变通方法(只保存为密钥找到的最后一个值): / p>

// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];

否则,如果单个键具有多个值是有效的,那么您应该考虑将值存储在每个List<string>键的string中。

例如:

var rct3Features = new Dictionary<string, List<string>>();
var rct4Features = new Dictionary<string, List<string>>();

foreach (string line in rct3Lines)
{
    string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);

    if (!rct3Features.ContainsKey(items[0]))
    {
        // No items for this key have been added, so create a new list
        // for the value with item[1] as the only item in the list
        rct3Features.Add(items[0], new List<string> { items[1] });
    }
    else
    {
        // This key already exists, so add item[1] to the existing list value
        rct3Features[items[0]].Add(items[1]);
    }
}

// To display your keys and values (testing)
foreach (KeyValuePair<string, List<string>> item in rct3Features)
{
    Console.WriteLine("The Key: {0} has values:", item.Key);
    foreach (string value in item.Value)
    {
        Console.WriteLine(" - {0}", value);
    }
}

答案 2 :(得分:4)

为了说明你遇到的问题,让我们看看一些代码......

Dictionary<string, string> test = new Dictionary<string, string>();

test.Add("Key1", "Value1");  // Works fine
test.Add("Key2", "Value2");  // Works fine
test.Add("Key1", "Value3");  // Fails because of duplicate key

字典具有键/值对的原因是一个功能,所以你可以这样做......

var myString = test["Key2"];  // myString is now Value2.

如果Dictionary有2个Key2,它就不知道要返回哪一个,所以它限制你使用一个唯一的键。

答案 3 :(得分:3)

如果在尝试添加新密钥时字典中已有密钥,则抛出异常。

rct3Lines中必须有多行,且第一个单词相同。您不能在同一个词典中使用相同的键有2个条目。

如果密钥已经存在,您需要决定要发生什么 - 如果您只想更新密钥存在的值,您可以简单地

rct3Features[items[0]]=items[1]

但是,如果不是,您可能想要测试密钥是否已存在:

if(rect3Features.ContainsKey(items[0]))
{
    //Do something
} 
else 
{
    //Do something else
}

答案 4 :(得分:3)

如果要“插入或替换”语义,请使用以下语法:

A[key] = value;     // <-- insert or replace semantics

它比在“ Add()”之前涉及“ ContainsKey()”或“ Remove()”的调用更为有效和可读。

所以在您的情况下:

rct3Features[items[0]] = items[1];

答案 5 :(得分:-3)

在向其添加任何项目之前清除字典。我不知道一个对象的字典在赋值期间如何影响另一个对象,但是在创建了具有相同键值对的另一个对象之后我得到了错误。

NB: 如果要在循环中添加项目,请确保在进入循环之前清除字典。

相关问题