如何在字典中分配key => value对?

Ran*_*rez 4 c# dictionary c#-4.0

这是我的代码:

string[] inputs = new[] {"1:2","5:90","7:12","1:70","29:60"};

//Declare Dictionary
var results = new Dictionary<int, int>();
//Dictionary<int, int> results = new Dictionary<int, int>();

foreach(string pair in inputs)
{
    string[] split = pair.Split(':');
    int key = int.Parse(split[0]);
    int value = int.Parse(split[1]);

    //Check for duplicate of the current ID being checked
    if (results.ContainsKey(key))
    {
        //If the current ID being checked is already in the Dictionary the Qty will be added
        //Dictionary gets Key=key and the Value=value; A new Key and Value is inserted inside the Dictionary
        results[key] = results[key] + value;
    }
    else
    {
        //if No duplicate is found just add the ID and Qty inside the Dictionary
        results[key] = value;
        //results.Add(key,value);
    }
}

var outputs = new List<string>();
foreach(var kvp in results)
{
    outputs.Add(string.Format("{0}:{1}", kvp.Key, kvp.Value));
}

// Turn this back into an array
string[] final = outputs.ToArray();
foreach(string s in final)
{
    Console.WriteLine(s);
}
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

我想知道在字典中分配key => value对之间是否存在差异.

方法一:

results[key] = value;
Run Code Online (Sandbox Code Playgroud)

方法2:

results.Add(key,value);
Run Code Online (Sandbox Code Playgroud)

在方法1中,函数Add()没有被调用,而是名为'results'的字典以某种方式通过在method1中声明代码来设置键值对,我假设它以某种方式在字典内自动添加键和值而不添加()被召唤.

我问这个是因为我现在是学生而且我正在学习C#.

先生/女士,你的答案会有很大的帮助,非常感谢.谢谢++

M.B*_*ock 6

Dictionary<TKey, TValue>索引器的设置方法(当你这样做,那叫一个results[key] = value;)是这样的:

set
{
    this.Insert(key, value, false);
}
Run Code Online (Sandbox Code Playgroud)

Add方法如下:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}
Run Code Online (Sandbox Code Playgroud)

唯一的区别是如果第三个参数为true,如果密钥已经存在,它将抛出异常.

旁注:反编译器是.NET开发人员的第二好朋友(第一个当然是调试器).这个答案来自mscorlib于ILSpy的开幕式.


Osk*_*lin 5

如果密钥存在于1)中,则覆盖该值.但是在2)它会引发异常,因为键需要是唯一的