LinQ ofType in Value
I have the following dictionary:
public Dictionary<string,object> Items;
Now I need to get all elements where the value The dictionary value is a specific type. (eg "int")
var intValues = Items.OfType<KeyValuePair<string,int>>
just doesn't work.
Non-LinQ code would look something like this:
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 main idea. But if possible, I would not create a new dictionary as a result.
source to share
Direct translation of your foreach
to LINQ would be as follows:
var intValues = Items.Where(item => item.Value is int)
.ToDictionary(item => item.Key, item => (int)item.Value);
So, first you first filter where item.Value
is int
, and then you create a dictionary from it with ToDictionary
where you passed those values ββto int
, to make sure the resulting dictionary is Dictionary<string, int>
. Since we've already filtered out non-integers, this cast will always succeed.
source to share