如何修改 KeyValuePair 值?

当我试图修改一个条目的值时,我遇到了一个问题,因为它只是一个只读字段。

KeyValuePair<Tkey, Tvalue>

我尝试过不同的选择,比如:

Dictionary<Tkey, Tvalue>

但是我也有同样的问题。有没有办法把值字段设置成一个新值?

113823 次浏览

KeyValuePair<TKey, TValue> is immutable. You need to create a new one with the modifified key or value. What you actually do next depends on your scenario, and what exactly you want to do...

You can't modify it, you can replace it with a new one.

var newEntry = new KeyValuePair<TKey, TValue>(oldEntry.Key, newValue);

or for dictionary:

dictionary[oldEntry.Key] = newValue;

Here, if you want to make KeyValuePair mutable.

Make a custom class.

public class KeyVal<Key, Val>
{
public Key Id { get; set; }
public Val Text { get; set; }


public KeyVal() { }


public KeyVal(Key key, Val val)
{
this.Id = key;
this.Text = val;
}
}

so we can make it use in wherever in KeyValuePair.

You cannot modify a KeyValuePair, but you can modify your dictionary values like this:

foreach (KeyValuePair<String, int> entry in dict.ToList())
{
dict[entry.Key] = entry.Value + 1;
}

or like this:

foreach (String entry in dict.Keys.ToList())
{
dict[entry] = dict[entry] + 1;
};

KeyValuePair is immutable,

namespace System.Collections.Generic
{
[Serializable]
public struct KeyValuePair<TKey, TValue>
{
public KeyValuePair(TKey key, TValue value);
public TKey Key { get; }
public TValue Value { get; }
public override string ToString();
}
}

If you have any existing value in KeyValuePair that you want to update, then You can try to remove the existing value and then add the modified value

For an example:

var list = new List<KeyValuePair<string, int>>();
list.Add(new KeyValuePair<string, int>("Cat", 1));
list.Add(new KeyValuePair<string, int>("Dog", 2));
list.Add(new KeyValuePair<string, int>("Rabbit", 4));


int removalStatus = list.RemoveAll(x => x.Key == "Rabbit");


if (removalStatus == 1)
{
list.Add(new KeyValuePair<string, int>("Rabbit", 5));
}

The KeyValuePair<TKey, TValue> is a struct and struct in C# is value type and mentioned to be immutable. The reason is obvious, the Dictionary<TKey,TValue> should be a high-performance data structure. Using a reference type instead of value type would use too much memory overhead. Unlike a directly stored value type in a dictionary, in addition the 32bit or 64bit references for each entry in the dictionary would be allocated. These references would be pointed to heap for entry instance. Overall performance would be decreased rapidly.

The Microsoft rules for choosing struct over class which Dictionary<TKey,TValue> satisfies:

✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

❌ AVOID defining a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
Dictionary<long, int> _rowItems = new Dictionary<long, int>();
_rowItems.Where(x => x.Value > 1).ToList().ForEach(x => { _rowItems[x.Key] = x.Value - 1; });

For Dictionary we can update values in this way based on some conditions.