Search code examples
c#dictionaryienumerableoftype

How to Get Key-Value Pairs of a Specific Type Only from Dictionary


I have an IDictionary (not generic, so I am dealing with object's here), and I would like to get from it only the elements in that IDictionary which correspond to a specific key type K and a specific value type V. There are a billion ways to do this, but the most elegant way I have found seems to be this:

Dictionary<K, V> dict = myIDictionary.OfType<KeyValuePair<K, V>>();

This compiles fine so I am assuming this method CAN work for a dictionary (it's declared by IEnumerable) but the resulting dictionary is empty, although there are definitely KVPs in there that meet those conditions. Obviously I was assuming that KeyValuePair<K, V> is the format it is expecting, since that's what's used in enumeration over a dictionary, but is it something else? Is there something I'm missing?


Solution

  • A non-generic IDictionary doesn't use a KeyValue<T,U> type, so you'll never have any matches.

    You would need to parse the DictionaryEntry items, and convert them:

    Dictionary<K,V> dict = myIDictionary
                              .Cast<DictionaryEntry>()
                              .Where(de => de.Key is K && de.Value is V)
                              .ToDictionary(de => (K)de.Key, de => (V)de.Value);