如何更新在c#字典中存储的值?

如何在字典Dictionary<string, int>中更新特定键的值?

782660 次浏览

只需指向字典中给定的键并赋一个新值:

myDictionary[myKey] = myNewValue;

通过将键作为索引访问是可能的

例如:

Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2

这里有一种通过索引进行更新的方法,类似于foo[x] = 9,其中x是键,9是值

var views = new Dictionary<string, bool>();


foreach (var g in grantMasks)
{
string m = g.ToString();
for (int i = 0; i <= m.Length; i++)
{
views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
}
}

你可以这样做:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
int val;
if (dic.TryGetValue(key, out val))
{
// yay, value exists!
dic[key] = val + newValue;
}
else
{
// darn, lets add the value
dic.Add(key, newValue);
}
}

你在这里得到的边是你检查并在访问字典的1次中获得相应的键的值。 如果您使用ContainsKey检查是否存在,并使用dic[key] = val + newValue;更新值,那么您将访问字典两次

使用LINQ:访问字典键并更改值

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);

这可能对你有用:

场景1:基本类型

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};


if(!dictToUpdate.ContainsKey(keyToMatchInDict))
dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

场景2:我用于List as Value的方法

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...


if(!dictToUpdate.ContainsKey(keyToMatch))
dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
dictToUpdate[keyToMatch] = objInValueListToAdd;

希望对需要帮助的人有用。

  1. 更新 -修改仅存在。为了避免使用索引器的副作用:

    int val;
    if (dic.TryGetValue(key, out val))
    {
    // key exist
    dic[key] = val;
    }
    
  2. update or (add new if value doesn't exist in dic)

    dic[key] = val;
    

    例如:

    d["Two"] = 2; // adds to dictionary because "two" not already present
    d["Two"] = 22; // updates dictionary because "two" is now present
    

这个扩展方法允许一个匹配谓词委托作为字典键选择器,和一个单独的委托来执行字典值替换,所以它对所使用的键/值对的类型完全开放:

public static void UpdateAll<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Func<TKey, TValue, bool> matchPredicate, Func<TValue, TValue> updatePredicate)
{
var keys = dictionary.Keys.Where(k => matchPredicate(k, dictionary[k])).ToList();
foreach (var key in keys)
{
dictionary[key] = updatePredicate(dictionary[key]);
}
}

使用示例:

    Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "One");
dict.Add(2, "Two");
dict.Add(3, "Three");


//Before
foreach(var kvp in dict){
Console.WriteLine(kvp.Value);
}


dict.UpdateAll(
matchPredicate: (k, v) => k >= 2, //Update any dictionary value where the key is >= 2
updatePredicate: (v) => v = v + " is greater than One"
);


//After
foreach(var kvp in dict){
Console.WriteLine(kvp.Value);
}

这个简单的检查将执行upsert,即更新或创建。

if(!dictionary.TryAdd(key, val))
{
dictionary[key] = val;
}

你也可以使用这个方法:

Dictionary<int,int> myDic = new();
if (myDic.ContainsKey(1))
{
myDic[1] = 1234; // or use += to update it
}

或按值:

if (myDic.ContainsValue(1))
{
//do something ...
}