How to modify a KeyValuePair value?

I got a problem when I try to modify the value of an item because its only a read only field.

KeyValuePair<Tkey, Tvalue>

I've tried different alternatives like:

Dictionary<Tkey, Tvalue>

but there I have the same problem. Is there a way to set the value field to an new value?


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.


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...