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