简体   繁体   中英

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?

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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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