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