How to check duplicate keys and remove the previous value from the dictionary?

I have Dictionaryone that contains values ​​with keys. According to my condition, I will have duplicate keys that are not strictly allowed in Dictionary. Now my question is: how to check the previous duplicate in the current one Dictionaryand delete it to add a new one?

+4
source share
6 answers

You can use the dictionary's ContainsKey () method to find out if the dictionary already contains your key or not

dict.ContainsKey(Key)

it returns a true if the dictionary contains a key, otherwise returns false

,

if(dict.ContainsKey(Key))
{
dict[key]=YOUR_NEW_VALUE;
}
else
{
 dict.Add ( key,YOUR_NEW_VALUE);
}
+3

, Value .

if (myDictionary.ContainsKey("key"))
{
    myDictionary["key"] = newValue;
}
+5

Using ContainsKey():

if(dict.ContainsKey(YourKey))
    dict[YourKey] = YourNewValue;

where dictis your vocabulary.

This line overwrites the new value for the key:

dict[YourKey] = YourNewValue;
+3
source
var uniqueValues = myDict.GroupBy(pair => pair.Value)
                         .Select(group => group.First())
                         .ToDictionary(pair => pair.Key, pair => pair.Value);
+2
source

Use the ContainsKey method to search for an existing key as follows:

 if (yourdictc.ContainsKey("YourKey"))
   { 
     //Do Somethig
   } 
+2
source

If you require add or update behavior, you do not need to call ContainsKey. Just assign a value and it will be updated if the key exists. If not, it will be added.

dict[key] = newValue;
0
source

Source: https://habr.com/ru/post/1530962/


All Articles