Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

Avoid duplicates in a Dictionary

I have a dictionary like this : Dictioanry<Guid,int>

In it , for example, i have 1234 , 5
                                        6666, 0

I'm looping and some GUID's might be duplicated which wont work because i cant have duplicate keys. Anyway to say: if this GUID is already in the dictionary, dont add it.
Avatar of Wikkard
Wikkard
Flag of Australia image

You could use a hashtable which wont allow duplicate keys:

System.Collections.Hashtable h = new Hashtable();
            h.Add("sdf", "Sdf");
            h.Add("sdf", "123123");//this line will throw exception because of duplicate key


I may have misunderstood your use of the term GUID, but the whole point of guids is that they will be unique. The chances of you generating a duplicate guid is very small, however still exists.


I just checked and the code below will cause and exception in the same manner as the hashtable example.

  System.Collections.Generic.Dictionary<string, string> d = new System.Collections.Generic.Dictionary<string,string>();
            d.Add("1234", "Sdfsdfsd");
            d.Add("1234", "sdfsdfsdfsdfd");


This should happen regardless of the keys type (guid, string whatever), it just wont allow duplicate keys.

prior to adding new item into dictionary double-check if the key already exists in it
However if you are getting GUIDs from System.Guid you shouldn't get any duplicates.
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string guid = System.Guid.NewGuid().ToString();
            if (!dict.ContainsKey(guid))
                dict.Add(guid, "your value");

Open in new window

As far I know ,this validation is already in place ,the Dictonary Component will never allow a duplicate key to be added;and it will throw an exception.

like Dict.Add("key",1)
Dict.Add("key",2)
executing these will throw an exception as "key" is a duplicate key
Yes it's in place, but why would you like to have an exception to be thrown if there is a single line of code available that avoids it?
Avatar of Camillia

ASKER

DreamsTech: is right. The validation is in place and it throws an error and crashes the app. I want to DO A CHECK : if key exits in the dictionary, skip and dont insert.

 How can I do this???
ASKER CERTIFIED SOLUTION
Avatar of tetorvik
tetorvik
Flag of Finland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ah yes, let me try. will post back.