Possible Duplicate:
Recreating a Dictionary from an IEnumerable
When using the Where method on a dictionary of type Dictionary<TKey, TValue> you ends up with a IEnumerable<KeyValuePair<TKey, TSource>> and that is breaking the datatype that I have choose at the beginning. I would like to return a dictionary.
Maybe I am not using the correct filter function. So how do you usually filter element from a dictionary?
Thanks
IDictionary<TKey, TValue>actually extendsIEnumerable<KeyValuePair<TKey, TValue>>. This is why you can use LINQ operators on anIDictionary<TKey, TValue>in the first place.However, LINQ operators return
IEnumerable<T>which are meant to provide deferred execution, meaning the results aren’t actually generated until you start iterating through theIEnumerable<T>.The
IEnumerable<T>implementation which is provided byIDictionary<TKey, TValue>comes by way of theICollection<T>interface (whereTis aKeyValuePair<TKey, TValue>), which means that if LINQ were to returnIDictionary<TKey, TValue>instead ofIEnumerable<KeyValuePair<TKey, TValue>>then it would have to materialize the list, violating it’s principals (hence theIEnumerable<KeyValuePair<TKey, TValue>>return value).Of course, the way around it is to call the
ToDictionaryextension method on theEnumerable class(as others have mentioned), but a little back-story never hurts.