views:

86

answers:

5

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

+1  A: 

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.

Darin Dimitrov
+1  A: 

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.

Sky Sanders
+5  A: 

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

Mauricio Scheffer
+4  A: 

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

Jon Skeet
I'm sorry, but you just reminded me of my favorite Jon Skeet Fact: If you have $5 and Jon Skeet has $5, Jon Skeet has more money than you. Lol. :)... +1
lucifer
I'm actually using it to store info about emails. I'm using the Key to store the senders email, and the value is holding the subject of the email
lucifer
@j-t-s: So what's the actual *meaning* of there being more than one email from a particular user? Do you need to store all the subjects, or just the latest one?
Jon Skeet
well, when i check for email, it will download all emails from the server and place the sender and subject into a Dictionary. But quite often my investor sends tonnes of emails everyday with the exact same subject. I think I've tried every type of List available but they all seem to be the same. I am checking out the ones provided in these answers but I was kinda hoping for something kinda simple
lucifer
A: 

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

Phil