Hi All
I need something like a Dictionary or a SortedList but i keep getting exceptions thrown when it receives two things that are the same... Is there another way around this?
Thanks
Hi All
I need something like a Dictionary or a SortedList but i keep getting exceptions thrown when it receives two things that are the same... Is there another way around this?
Thanks
The key in a dictionary or a sorted list the key should be unique: that's the purpose of hashtables. You could use List<KeyValuePair<TKey, TValue>>
or KeyValuePair<TKey, TValue>[]
instead but of course you won't be able to locate a value by key as you may have duplicates.
Both a dictionary and a sortedlist are keyed, meaning that the keys must be unique.
You could check before you add the item, e.g. dic.ContainsKey(key)
or list.Contains(item)
before adding.
If you would like to be able to add multiple values for a single key you can use a NameValueCollection
.
You probably want a multimap. You can simulate one with a Dictionary<Key, List<Value>>
. Also see this question, it has some multimap implementations.
My guess is that you're using
dictionary.Add(key, value);
If you're happy just replacing the existing key/value pair, then just use the indexer:
dictionary[key] = value;
If you want to have multiple values for the same key, see the other answers :)
If what you're asking for is a dictionary where the value is the same as the key, then there's a generic collection type named 'HashSet' in the System.Collections.Generic namespace which looks like it serves that purpose.
If you're just asking about an exception generated when adding to your dictionary, I think Jon Skeet is probably right on what is probably your issue.
HashSet: