user2357446
user2357446

Reputation: 676

Nested LINQ for Dictionary

Using C#, I have the following Dictionary

Dictionary<MyClass, List<MyOtherClass>> myDictionary;

I am trying to write a LINQ query that will select every instance of MyOtherClass inside each key-value of my Dictionary. So far I have the following:

var whatImLookingFor = myDictionary.SelectMany(x => x.Value).Select(y => y.myProperty == someCompareValue);

This compiles and runs, but whatImLookingFor doesn't seem to be able to be cast to a collection of MyOtherClass objects. If I try to it says that I am trying to convert from a bool to MyOtherClass.

Is there a special way to handle nested LINQ queries when dealing with Dictionaries?

Upvotes: 0

Views: 68

Answers (3)

sporkasaurus
sporkasaurus

Reputation: 31

As others have mentioned, you're selecting a list of bools by doing that; you're effectively selecting the result of testing each value in the lists against someCompareValue, in the order that the dictionary is enumerating the key value pairs.

You can use where in place of your second select. It's a bit more verbose, but I tend to find linq of this form more maintainable when queries get more complicated:

    var whatImLookingFor = from kvp in myDictionary
                           from v in kvp.Value
                           where v.myProperty == someCompareValue
                           select v;

Upvotes: 2

John Bustos
John Bustos

Reputation: 19574

You'd want to be using Where rather than Select and don't even need the SelectMany - You could just write it as:

var whatImLookingFor = myDictionary.Values.Where(y => y.myProperty == someCompareValue);

Hope that helps!

Upvotes: 0

Hopeless
Hopeless

Reputation: 4773

You are actually selecting a bool expression from each entry. I think you mean Where in place of Select like this:

var whatImLookingFor = myDictionary.SelectMany(x => x.Value)
                                   .Where(y => y.myProperty == someCompareValue);

Upvotes: 2

Related Questions