如何在字典中分配键值对?

4
这是我的代码:
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();

我可以帮您翻译成如下内容:

我想知道在字典中分配一个键值对是否存在差异。

方法1:

results[key] = value;

方法二:

results.Add(key,value);

在方法1中,未调用函数Add(),而是通过在方法1中声明的代码对名为“results”的Dictionary进行了一种方式的Key-Value对赋值。我猜测它会自动向字典中添加键和值,而无需调用Add()。
我之所以问这个问题,是因为我目前正在学习C#,希望您的答案能够帮助我。
先生/女士,您的回答将非常有帮助并受到高度赞赏。谢谢++

1
可能是添加字典的不同方式的重复问题。 - Oskar Kjellin
2个回答

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

set
{
    this.Insert(key, value, false);
}
< p > Add 方法如下:

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

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

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


5

如果在1)中存在该键,则该值将被覆盖。但是在2)中,它会抛出异常,因为键需要唯一。


澄清一下,在1中,如果键存在,则会覆盖,而不是键。 - OnResolve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接