Hans
Hans

Reputation: 565

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?

Upvotes: 2

Views: 1181

Answers (2)

Shravan Sunder
Shravan Sunder

Reputation: 31

Try this:

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

Upvotes: 1

aquinas
aquinas

Reputation: 23786

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

Upvotes: 6

Related Questions