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

时间:2012-02-16 13:26:23

标签: 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[] 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();

我想知道在字典中分配key =&gt;值对之间是否存在差异。

方法一:

results[key] = value;

方法2:

results.Add(key,value);

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

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

先生/女士,您的回答将会有很大的帮助,非常感谢。谢谢++

2 个答案:

答案 0 :(得分:6)

Dictionary<TKey, TValue>索引器的set方法(执行results[key] = value;时调用的方法)如下所示:

set
{
    this.Insert(key, value, false);
}

Add方法如下:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

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

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

答案 1 :(得分:5)

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

相关问题