Accepted answer

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)


You can do

var result = Items.Where(x => x.Value is int)
                  .ToDictionary(x => x.Key, x => x.Value);


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.


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

Related Articles