Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for duplicate keys and delete previous value from Dictionary?

Tags:

c#

dictionary

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?

like image 506
Ram Avatar asked Mar 10 '14 11:03

Ram


People also ask

How do dictionary handle duplicate keys?

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.

Can you have two of the same keys in a 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.

Does Dictionary accept duplicate keys?

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


2 Answers

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);
}
like image 98
Sumeshk Avatar answered Nov 15 '22 05:11

Sumeshk


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;
}
like image 23
DonBoitnott Avatar answered Nov 15 '22 04:11

DonBoitnott