Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The property KeyValuePair<TKey, Tvalue>.Value has no setter

I'm using a Dictionary<int, KeyValuePair<bool, int>> to hold data.

From time to time I need to increment the int in the KeyValuePair, but it won't let me, because it has no setter. Is there a way to increment it?

Code sample:

Dictionary<int, KeyValuePair<bool, int>> mDictionary = 
    new Dictionary<int, KeyValuePair<bool, int>>();

mDictionary[trapType].Value++;
//Error: The property KeyValuePair<TKey, Tvalue>>.Value has no setter
like image 950
choppy Avatar asked May 14 '12 08:05

choppy


People also ask

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.

What is KeyValuePair C#?

The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.

Can key-value pairs null?

If the key or value is NULL (i.e. SQL NULL), the key-value pair is omitted from the resulting object. A key-value pair consisting of a not-null string as key and a JSON NULL as value (i.e. PARSE_JSON('NULL')) is not omitted. The constructed object does not necessarily preserve the original order of the key-value pairs.


1 Answers

Is there a way to increment it?

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

You'd have to write something like this:

var existingValue = mDictionary[trapType];
var newValue = new KeyValuePair<bool, int>(existingValue.Key,
                                           existingValue.Value + 1);
mDictionary[trapType] = newValue;

It's pretty ugly though - do you really need the value to be a KeyValuePair?

like image 65
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet