ChatGPT解决这个技术问题 Extra ChatGPT

如何在 C# 中更新存储在 Dictionary 中的值?

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

我有一个复杂类型存储为字典中的值。当我想更改存储值的属性时,我得到 CS1612。因此我必须采取一种方法: var v = dict[c]; v.dprop = c.sprop;字典[c] = v;
peter70,只有结构,这是因为结构是按值返回的,所以“更新”它们只会更新它的临时本地副本。

I
IT ppl

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

myDictionary[myKey] = myNewValue;

这个操作的有趣之处在于,它通过 UPSERT(key, value) 转换成字典。杰出的!
正如皮尼所说,这应该是问题的答案。由于正确的事情并改变它。
@Philm,一个巨大的缺点是,这种方法被视为修改整个字典,换句话说,它不仅仅是更新。
@nevelis, var dict = new Dictionary() { { "a" , 0 }, { "b", 0 }, }; foreach (var key in dict.Keys) dict[key] = 1;如果它只是对值的更新,则在迭代键时不会出现异常,因为从表面上看,一个与另一个无关。
@greenoldman 啊,我明白你的意思,我误解了你所说的“修改整个字典”的意思,你指的是它使任何当前的迭代器无效,对吧?
A
Amit

可以通过将键作为索引访问

例如:

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

如果 List 中没有“test”项,则 list["test"] = list["test"] + 1;将引发 KeyNotFoundException!不存在的索引器的纯分配将起作用。列表[“测试”] = 1;
你也可以使用 list["test"]++; 吗?
@aufty 你可以写 ++dictionary["test"];dictionary["test"]++; 但前提是字典中有一个键值为“test”的条目 - 例如:if(dictionary.ContainsKey("test")) ++dictionary["test"]; else dictionary["test"] = 1; // create entry with key "test"
m
max_force

您可以遵循以下方法:

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; 更新值,那么您将访问字典两次。


您可以使用 dic[key] = newvalue; 而不是 dic.Add(key, newValue);
如果您执行“dic[key] = value”并且“key”不存在,会发生什么?
@superpuccio 你得到一个 KeyNotFoundException
@ntroncos 不正确,它将使用提供的值将该键添加到字典中。 += 对不存在的键不起作用,因为它只是 dic[key] = value + dic[key] 的语法糖。
这应该是问题的答案,因为它涉及更新字典而不仅仅是添加字典。
C
Community

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

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

我什至不明白这是如何工作的,但这太棒了
对于这么简单的事情,创建另一个字典对我来说没有意义。检查ccalboni的答案。
我认为这是一个很好的答案。它不需要您知道每个键字符串
第二行(LINQ 语句)每次都会创建整个字典的副本。不是一个好主意。
D
Dean Seo

这是一种通过索引进行更新的方法,类似于 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;
    }
}

m[i].Equals('1') 已经计算为布尔值,所以添加 ? true : false 不是必须的
我不知道这个逻辑有多有效,但我喜欢 For 循环的想法。 :)
s
saad bin sami

这个简单的检查将做一个 upsert 即更新或创建。

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

为什么不简单地做dictionary[key] = value;这将直接更新值。
请注意,这个答案是关于 upsert,即更新或创建。而不是简单地更新。 @Deb
V
Vlad

更新 - 仅修改存在的。为了避免索引器使用的副作用: int val; if (dic.TryGetValue(key, out val)) { // 键存在 dic[key] = val; } 更新或(如果 dic 中不存在值,则添加新值) dic[key] = val;例如:d["Two"] = 2; // 添加到字典,因为 "two" 不存在 d["Two"] = 22; // 更新字典,因为 "two" 现在存在


M
Mozart AlKhateeb

这可能对您有用:

场景一:原始类型

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;

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


B
BobT

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

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);
    }