Search code examples
c#linqkeyvaluepair

LINQ to List<KeyValuePair>


I'm currently working on an .NET Framework 4.7.2 application. I'm working on a LINQ query selecting objects from the given data structure:

List<KeyValuePair<int, Dictionary<string, object>>>

It is a list of dynamic objects. I need to select all elements from the list, where the value in the dictionary is true, the key would be IsDummy in this case.

The following image shows the data structure xyz in debug mode:

enter image description here

var result = xyz
    .Select(a => a.Value)
    .SelectMany(b => b)
    .Where(c => c.Key == "IsDummy" && (bool)c.Value == true);

I would like to select a List<KeyValuePair<int, Dictionary<string, object>>> where the value object in the dictionary is of type boolean and has the value true.

Unfortunately my current query doesn't work correctly.

Do you know how to solve this LINQ query? It is a bit tricky because of the KeyValuePair and Dictionary within the list.

Thank you very much!


Solution

  • This should work:

    var result = xyz
        .Where(kv => kv.Value.TryGetValue("IsDummy", out object value) 
                     && value is bool b && b); // pattern matching C#7
    

    Non C#7 version:

    ...
    && value is bool && (bool)value);