Jas*_*n W 22 c# dictionary exception
我一直收到以下代码的错误:
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谚语,
"已经添加了具有相同键的项目."
我不确定几个谷歌搜索如何解决这个问题.
稍后在代码中我需要访问字典以获得比较函数:
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");
        //}
    //}
}
此功能尚未完成,但我正在尝试解决此异常.有什么方法可以解决这个异常错误,并保持对字典的访问以便与此函数一起使用?谢谢
小智 33
这个错误是相当不言自明的.字典键是唯一的,您不能有多个相同的键.要解决此问题,您应该像这样修改代码:
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添加新条目.
如果您想要“插入或替换”语义,请使用以下语法:
A[key] = value;     // <-- insert or replace semantics
它比在“Add()”之前涉及“ContainsKey()”或“Remove()”的调用更有效和可读。
所以在你的情况下:
rct3Features[items[0]] = items[1];
正如其他人所说,你不止一次地添加相同的密钥.如果这不是一个有效的场景,那么检查Jdinklage Morgoone的答案(只保存为密钥找到的第一个值),或者,考虑这个解决方法(只保存为密钥找到的最后一个值):
// This will always overwrite the existing value if one is already stored for this key
rct3Features[items[0]] = items[1];
否则,如果单个键具有多个值是有效的,则应考虑将值存储在List<string>每个string键的a中.
例如:
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);
    }
}
为了说明您遇到的问题,让我们看一些代码...
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,它不知道要返回哪一个,因此它会将您限制为唯一键。