简体   繁体   English

C#如何使用Linq根据Value的类型查询Dictionary的条目子集?

[英]C# How do you query a subset of a Dictionary's entries based on the Value's type using Linq?

In C# using Linq, is it possible to extract a subset of a Dictionary's entries based on the type of the Value, and cast it as a Dictionary with that type as value? 在使用Linq的C#中,是否可以基于Value的类型提取Dictionary条目的子集,并将其转换为具有该类型作为value的Dictionary?

Basically, if you have a Dictionary like this one: 基本上,如果你有一个像这样的词典:

Dictionary<string, Object> Data;

Can you then do something like: 你可以做一些像:

Dictionary<string, int> IntData = Data.Query();

Such that the new Dictionary gets all the entires whose Value is of Type int. 这样,新的Dictionary就可以得到Value为int类型的所有整数。 Is this possible? 这可能吗?

Dictionary<string, int> IntData = Data.Where(k => k.Value is int)
   .ToDictionary(kv => kv.Key, kv => (int) kv.Value);

Try this: 尝试这个:

Dictionary<string, int> IntData = Data
.Where(q => q.Value.GetType() == typeof(int))
.ToDictionary(q => q.Key, q => (int)q.Value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM