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?
default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.
To add key-value pair in C# Dictionary, firstly declare a Dictionary. IDictionary<int, string> d = new Dictionary<int, string>(); Now, add elements with KeyValuePair. d.
You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With