I have a Dictionary
which contains values with keys. According to my condition, I will have duplicate keys which are strictly not permitted in Dictionary
. Now my question is: how to check for the previous duplicate key in the current Dictionary
and delete it to add the new?
If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
[C#] Dictionary with duplicate keys The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
You can use the ContainsKey() method of the Dictionary to find out whether Dictionary already contains your key or not
dict.ContainsKey(Key)
it returns a true if the Dictionary contains key otherwise returns a false
you don't need to delete the key you can just overwrite the value
if(dict.ContainsKey(Key))
{
dict[key]=YOUR_NEW_VALUE;
}
else
{
dict.Add ( key,YOUR_NEW_VALUE);
}
My advice would be to think of deleting as simply overwriting the Value
member of the matching entry.
if (myDictionary.ContainsKey("key"))
{
myDictionary["key"] = newValue;
}
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