C# “参数例外”;已添加具有相同密钥的项";

C# “参数例外”;已添加具有相同密钥的项";,c#,exception,dictionary,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 =

我不断收到以下代码的错误:

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);
    //}

}

此函数尚未完成,但我正在尝试解决此异常。有什么方法可以修复此异常错误,并保持对字典的访问以用于此函数?谢谢

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

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);
    //}
}
Dictionary rct3Features=newdictionary();
字典rct4Features=新字典();
foreach(RCT3行中的字符串行)
{
string[]items=line.Split(新字符串[]{”“},2,StringSplitOptions.None);
如果(!rct3Features.ContainsKey(项[0]))
{
添加(项目[0],项目[1]);
}
////把字典打印出来(看看是否有用)
//foreach(rct3Features中的KeyValuePair项)
//{
//Console.WriteLine(item.Key+“”+item.Value);
//}
}

这个简单的
if
语句确保您仅在键(
items[0]
)不存在时才尝试向字典添加新条目。

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

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

如果字典有2个键2,它不知道返回哪个键,因此它将您限制为一个唯一的键。

当您尝试添加新键时,如果字典中已有键,则会引发该异常

rct3Lines
中必须有多行具有相同的第一个单词。同一词典中不能有两个条目具有相同的键

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

rct3Features[items[0]]=items[1]
但是,如果没有,您可能需要测试密钥是否已经存在,包括:

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

正如其他人所说,您多次添加相同的密钥。如果这不是一个有效的方案,那么检查Jdinklage Morgoone的答案(它只保存为键找到的第一个值),或者,考虑这个解决方案(它只保存了为键找到的最后一个值):

否则,如果对一个键有多个值是有效的,那么您应该考虑将值存储在<代码>列表> />代码中。 例如:

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);
    }
}
var rct3Features=newdictionary();
var rct4Features=新字典();
foreach(RCT3行中的字符串行)
{
string[]items=line.Split(新字符串[]{”“},2,StringSplitOptions.None);
如果(!rct3Features.ContainsKey(项[0]))
{
//尚未添加此键的任何项,因此请创建一个新列表
//对于将项[1]作为列表中唯一项的值
添加(项[0],新列表{items[1]});
}
其他的
{
//此键已存在,请将项[1]添加到现有列表值
RCT3功能[项目[0]]。添加(项目[1]);
}
}
//显示键和值的步骤(测试)
foreach(rct3Features中的KeyValuePair项)
{
WriteLine(“键:{0}有值:”,item.Key);
foreach(item.value中的字符串值)
{
WriteLine(“-{0}”,值);
}
}

在添加任何项目之前,请清除字典。我不知道一个对象的字典在赋值过程中如何影响另一个对象的字典,但我在创建另一个具有相同键、值对的对象后出错

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

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

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

停止尝试添加具有相同密钥的多个项目。也许您应该在添加时添加一个检查,以确保密钥不存在。否则,我们无法知道正确的操作步骤是什么,因为如果存在重复的项目,您几乎没有提供任何关于您希望发生什么的信息。为什么您有重复的密钥?如果每个键需要一个以上的值,则应使用
字典
。有关详细信息,请查看下面的答案,但您可以使用不同的语法替换Add。如果密钥已存在,则以下内容将覆盖该密钥的现有值:
rct3Features[items[0]]=items[1]
newdictionary()
,因此无需在构造后清除它。在每次调用
Add
之前清除它将停止异常,但只会导致字典中出现最后一项。你确定这是个好建议吗?
// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];
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);
    }
}
A[key] = value;     // <-- insert or replace semantics
rct3Features[items[0]] = items[1];