Reputation: 9295
I have the following Dictionary:
public Dictionary<string,object> Items;
Now I need to get all Items where the Value of the Dictionary-item is from a specific type. (e.g. "int")
var intValues = Items.OfType<KeyValuePair<string,int>>
simply does not work.
Code without LinQ would be something like:
var intValues=new Dictionary<string,int>()
foreach (var oldVal in Items) {
if (oldVal.Value is int) {
intValues.add(oldVal.Key, oldVal.Value);
}
}
(Update) my example should show the basic idea. But if possible I would avoid to create a new Dictionary as a result.
Upvotes: 3
Views: 413
Reputation: 118977
You can use the is
operator on the Value
property:
var intValues = Items.Where(x => x.Value is int);
If you want an actual Dictionary<string,int>
at the end just add:
.ToDictionary(v=> v.Key, v=> (int)v.Value)
Upvotes: 4
Reputation: 48568
You can do
var result = Items.Where(x => x.Value is int)
.ToDictionary(x => x.Key, x => x.Value);
Upvotes: 2
Reputation: 8868
Try with this:
var intValue = Items
.Where(x => x.Value is int) // filter per Value is int
.ToDictionary(x => x.Key, x => (int)x.Value); // create a new dictionary converting Value to int
Upvotes: 4
Reputation: 387707
The direct translation of your foreach
would be the following in LINQ:
var intValues = Items.Where(item => item.Value is int)
.ToDictionary(item => item.Key, item => (int)item.Value);
So basically, you filter first for where the item.Value
is an int
, and then you create a dictionary from it using ToDictionary
where you cast those values to int
to make sure that the resulting dictionary is a Dictionary<string, int>
. Since we filtered non-integers already, this type cast will always succeed.
Upvotes: 7