KeyValuePair vs. DictionaryEntry
[Krzysztof Cwalina]
We discussed a problem with
implementation of IEnumerable on
Dictionary<K,V>. What type should
IEnumerable.GetEnumerator().Current
return? KeyValuePair<K,V> or
DictionaryEntry? Same for
ICollection.CopyTo. Instances of what
type should be copied to the array?
We decided the following: IEnumerable
and ICollection interface
implementations will use
KeyValuePair<K,V> as the item type.
IDictionary specific members
(GetEnumerator returning
IDictionaryEnumerator) will use
DictionaryEntry as the item type.
The reason is that we are in a process
of making a change where
IEnumerator<T> would extend
IEnumerator. It would be very strange
if walking the hierarchy from
Dictionary<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.
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.
Dictionary is generic type that contains a collection of key-value pairs. Dictionary is fast for lookup operations, because is using hash function internally. That means, all the keys must be unique in dictionary.
Consider this examples:
List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>();
pairs.Add(new KeyValuePair<int, string>(1, "Miroslav"));
pairs.Add(new KeyValuePair<int, string>(2, "Naomi"));
pairs.Add(new KeyValuePair<int, string>(2, "Ingrid"));
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Miroslav");
dict.Add(2, "Naomi");
dict.Add(2, "Ingrid"); // System.ArgumentException: An item with the same key has already been added.
So you should always consider two at least two things:
Do you want to search concrete items in dictionary?
Do you want to have some fields
non-unique (for example pairs: firstname/lastname).