What is the difference between a List of KeyValuePair and a Dictionary for the same types? Is there an appropriate time to use one or the other?
views:
467answers:
6In short, the list does not enforce uniqueness of either the key or the value, so if you need that semantic then that's what you should use.
When you don't need fast lookups on key - maintaining the hashtable used by Dictionary
has a certain overhead.
From http://blogs.msdn.com/bclteam/archive/2004/09/03/225473.aspx:
KeyValuePair
vs.DictionaryEntry
[Krzysztof Cwalina]We discussed a problem with implementation of
IEnumerable
onDictionary<K,V>
. What type shouldIEnumerable.GetEnumerator().Current
return?KeyValuePair<K,V>
orDictionaryEntry
? Same forICollection.CopyTo
. Instances of what type should be copied to the array?We decided the following:
IEnumerable
andICollection
interface implementations will useKeyValuePair<K,V>
as the item type.IDictionary
specific members (GetEnumerator
returningIDictionaryEnumerator
) will useDictionaryEntry
as the item type.The reason is that we are in a process of making a change where
IEnumerator<T>
would extendIEnumerator
. It would be very strange if walking the hierarchy fromDictionary<K,V>
->IEnumerable<T>
->IEnumerable
we suddenly changed the type of the item returned from enumerators.
In SOAP webservices for silverlight, we have found that Dictionary's do not serialize. This would be a situation where you would use a List of KeyValuePair over a Dictionary.
.
The List would also be useful when you care about the order of the items.
Further to Phillip Ngan's answer, SOAP or otherwise, you cannot XML serialize objects that implements IDictionary.
Q: Why can't I serialize hashtables?
A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.