如何在字典中分配key =>值对? [英] How to assign key=>value pairs in a 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 => value对是否存在区别。
I want to know if the difference if there is between assigning a key=>value pair in a dictionary.
方法1:
results[key] = value;
方法2:
results.Add(key,value);
在方法1中,未调用功能Add(),而是分配了名为结果的字典通过在method1中声明代码以某种方式设置键-值对,我假设它以某种方式在不调用Add()的情况下自动在字典中添加了键和值。
In method 1, the function Add() was not called but instead the Dictionary named 'results' assigns somehow sets a Key-Value pair by stating code in method1, I assume that it somehow adds the key and value inside the dictionary automatically without Add() being called.
I之所以这样问,是因为我目前是学生,并且我正在学习C#。
I'm asking this because I'm currently a student and I'm studying C# right now.
先生/女士,您的回答将对您有所帮助,并且非常感谢。谢谢++
Sir/Ma'am, your answers would be of great help and be very much appreciated. Thank you++
推荐答案
索引器的设置方法 Dictionary< TKey,TValue>
(当您执行 results [key] = value;
时调用的那个)看起来像:
The Dictionary<TKey, TValue>
indexer's set method (the one that is called when you do results[key] = value;
) looks like:
set
{
this.Insert(key, value, false);
}
添加
方法看起来像这样:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
唯一的区别是,如果第三个参数为true,则会抛出一个
The only difference being if the third parameter is true, it'll throw an exception if the key already exists.
侧面说明:反编译器是.NET开发人员的第二好朋友(当然,第一个是调试器)。这个答案来自在ILSpy中打开 mscorlib
。
Side note: A decompiler is the .NET developers second best friend (the first of course being the debugger). This answer came from opening mscorlib
in ILSpy.
这篇关于如何在字典中分配key =>值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!