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.

+3


source to share


4 answers


You can use the operator is

on the property Value

:

var intValues = Items.Where(x => x.Value is int);

      



If you want the actual one Dictionary<string,int>

at the end to just add:

.ToDictionary(v=> v.Key, v=> (int)v.Value)

      

+4


source


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.

+7


source


Try the following:

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

      

+4


source


You can do

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

      

+2


source







All Articles