C# 如何分配密钥=>;字典中的值对?

C# 如何分配密钥=>;字典中的值对?,c#,c#-4.0,dictionary,C#,C# 4.0,Dictionary,这是我的密码: 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[] 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();
方法2:

results.Add(key,value);
在方法1中,没有调用函数Add(),而是名为“results”的字典通过在方法1中声明代码以某种方式分配一个键值对。我假设它以某种方式自动在字典中添加键值,而不调用Add()

我问这个是因为我现在是一名学生,我正在学习C#

先生/女士,您的回答将非常有帮助,我们将不胜感激。谢谢+++

如果键存在于1)中,则该值将被覆盖。但是在2)中,它会抛出一个异常,因为键需要是唯一的字典
索引器的set方法(在执行
结果[key]=value;
时调用的方法)如下所示:

set
{
    this.Insert(key, value, false);
}
public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}
Add
方法如下所示:

set
{
    this.Insert(key, value, false);
}
public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}
唯一的区别是,如果第三个参数为true,那么如果该键已经存在,它将抛出异常


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

为了澄清,在1中,如果键存在,则覆盖值,而不是键。可能的