Camillia
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.
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.
I just checked and the code below will cause and exception in the same manner as the hashtable example.
System.Collections.Generic .Dictionar y<string, string> d = new System.Collections.Generic .Dictionar y<string,s tring>();
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.
System.Collections.Generic
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.
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");
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
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?
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???
How can I do this???
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ah yes, let me try. will post back.
System.Collections.Hashtab
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.