【问题标题】:How to assign key=>value pairs in a Dictionary?如何在字典中分配键=>值对?
【发布时间】:2012-02-16 13:26:22
【问题描述】:

这是我的代码:

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 对之间是否存在差异。

方法一:

results[key] = value;

方法二:

results.Add(key,value);

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

我之所以问这个问题是因为我目前是一名学生,并且正在学习 C#。

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

【问题讨论】:

标签: c# c#-4.0 dictionary


【解决方案1】:

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

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

Add 方法如下所示:

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 澄清一下,在 1 中,如果键存在,则覆盖 ,而不是键。
    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2013-08-13
    相关资源
    最近更新 更多