Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify a KeyValuePair value?

Tags:

c#

.net

key-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?

like image 226
Kimbo Avatar asked Nov 19 '12 13:11

Kimbo


People also ask

What is the default value of KeyValuePair?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

Is KeyValuePair immutable?

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.

How do you assign a key-value pair in C#?

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.

Can KeyValuePair have duplicate keys?

You can use List<KeyValuePair<string,int>> . This will store a list of KeyValuePair 's that can be duplicate.


2 Answers

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; 
like image 192
deerchao Avatar answered Sep 23 '22 02:09

deerchao


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.

like image 29
maulin shah Avatar answered Sep 22 '22 02:09

maulin shah