Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
dictionary.Add(1,"one");
dictionary.Add(1,"one");


dictionary.Add(1,"one"); //how to check if following pair of key and value already exists in a dictionery i want to check before Adding to the dictionary
if
{
(1,"one"); if following set of key value do not exixts
dictionary.ADD(1,"one");

}

What I have tried:

C#
how to check if following pair of key and value already exists in a 
Posted
Updated 22-Nov-16 23:27pm

 
Share this answer
 
As you've probably discovered, if you Add(key, value) to a Dictionary that already has an entry with the same key, it throws an ArgumentException. It is not possible to have multiple entries with the same key.
If you want to add the value if the key is not present then try this:
C#
Dictionary<int, string> dict = new Dictionary<int, string>();
// initial value for demonstration
dict.Add(1, "umpteen");
dict.Add(2, "di");
// later
if (!dict.Contains(1))
  dict.Add(1, "mono");
// nothing changed in dict
if (!dict.Contains(3))
  dict.Add(3, "three");
// A new key-value pair was added

If all you want it to ensure that a key-value pair exists in the Dictionary, no matter if there is already a key-value pair with the same key and either the same or a different value, then instead of Adding to the Dictionary, just assign into it:
C#
// assume dict as we left it above...
dict[1] = "mono";
dict[2] = "di";
dict[3] = "tri";
dict[4] = "quad";

None of those assignments threw an exception and all 4 entries in the dict are set.
 
Share this answer
 
You can use below method to check whether a key is exist or not
C#
ContainsKey(TKey)


And this to check a value
C#
ContainsValue(TValue)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900