开发者

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 开发者_Go百科around this?

Thanks


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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜