asp.net Dictionary <string,string>基于键值的更新项</string,string>

时间:2013-03-24 13:52:55

标签: c# asp.net collections dictionary

我有一个Dictionary对象:

protected Dictionary<string,string> myDict;

我希望能够通过密钥搜索字典并更新该密钥/值对的值。

if (!myDict.ContainsKey(key))
{
    myDict.Add(key, value); //if key is not found in the collection add it.
}
else //if it is found then update it.
{
    Update[Key].Value with myValue
}

有没有办法做到以上几点?如何通过检查密钥更新密钥的值? 在else语句中匹配伪代码的实际代码是什么?

3 个答案:

答案 0 :(得分:3)

你可以做到

myDict[key] = value;

如果词典已包含密钥,则会更新。否则,它就会被创建。

答案 1 :(得分:2)

您可以使用键找到值并指定一个新值:

myDict[myKey] = yourNewValue;

答案 2 :(得分:0)

如果我理解正确的话,应该是直截了当的:

if (!myDict.ContainsKey(key))
{
    myDict.Add(key, value); //if key is not found in the collection add it.
}
else //if it is found then update it.
{
    myDict[key] = value;
}