[英]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: 我有一个IDictionary(不是泛型的,所以我在这里处理object
),我想从中获取该IDictionary中仅对应于特定键类型K和特定值类型V的元素。十亿种方法,但是我发现的最优雅的方法似乎是这样的:
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. 这可以很好地编译,因此我假设此方法可以用于字典(由IEnumerable声明),但是结果字典为空,尽管其中肯定有满足这些条件的KVP。 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? 显然,我假设KeyValuePair<K, V>
是它期望的格式,因为这是在字典枚举中使用的格式,但是还有其他吗? Is there something I'm missing? 有什么我想念的吗?
A non-generic IDictionary
doesn't use a KeyValue<T,U>
type, so you'll never have any matches. 非通用IDictionary
不使用KeyValue<T,U>
类型,因此您永远不会有任何匹配项。
You would need to parse the DictionaryEntry
items, and convert them: 您将需要解析DictionaryEntry
项目,并将其转换为:
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);
The OfType
function does filter the list based on the specified type... but you don't have anything of the type KeyValuePair<K,V>
in your base IDictionary
. OfType
函数会根据指定的类型过滤列表...但是您的基本IDictionary
没有类型为KeyValuePair<K,V>
任何内容。 You've only got whatever type the non-generic IDictionary
object contains (I'm not positive at the moment - maybe DictionaryEntry
?). 您只有非通用IDictionary
对象包含的任何类型(我目前不太肯定-也许DictionaryEntry
吗?)。 Even if it "matches" by the generic types of the pair, it's not really the same outer type. 即使它通过该对的通用类型“匹配”,也不是真正相同的外部类型。
So that function won't do what you're looking for. 因此,该功能无法满足您的需求。 You need to do something with a Where statement. 您需要对Where语句进行处理。 Something like: 就像是:
var dict = myIDictionary.Where(e => e.Key is typeof(K) && e.value is typeof(V))
though that is straight pseudocode, not positive what the actual syntax is. 虽然那是纯伪代码,但不能肯定实际语法是什么。
Edit: Looks like Reed has the full solution spelled out quite nicely. 编辑:看起来里德(Reed)很好地阐明了完整的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.