anon271334
anon271334

Reputation:

Dictionary with Exact Same Keys and Values

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

Upvotes: 4

Views: 3005

Answers (5)

Phil
Phil

Reputation: 2715

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:

http://msdn.microsoft.com/en-us/library/bb359438.aspx

Upvotes: 0

Mauricio Scheffer
Mauricio Scheffer

Reputation: 99730

You probably want a multimap. You can simulate one with a Dictionary<Key, List<Value>>. Also see this question, it has some multimap implementations.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500665

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 :)

Upvotes: 4

Sky Sanders
Sky Sanders

Reputation: 37084

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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.

Upvotes: 0

Related Questions