Using IList.Contains<> to search nested members?
-
I cannot figure out the syntax for using the LINQ extensions on IList (and other interfaces) to search for values that are in nested objects. For instance, I have a List<foo>, where object foo contains two other objects, each of which have field "data". How do I use List.Contains<foo>("hello") to search for a foo object where foo.nestedobject.data = hello?
-
I cannot figure out the syntax for using the LINQ extensions on IList (and other interfaces) to search for values that are in nested objects. For instance, I have a List<foo>, where object foo contains two other objects, each of which have field "data". How do I use List.Contains<foo>("hello") to search for a foo object where foo.nestedobject.data = hello?
Why not ask in the LINQ forum where the LINQ guru's hang out?
-
Why not ask in the LINQ forum where the LINQ guru's hang out?
Thanks. I asked here because it's not obvious that object.contains() is actually a LINQ extension. Sadly, you can't do what I want with object.contains(), which does not let you compare nested values directly. Turns out that what I need is
foo.Any(f => f.bar.data == "hello")
Which makes me a little sad, because
foo.Contains(nested value I was looking for)
would have been a lot simpler than having to break out my book and re-learn lambdas. Oh well, wave of the future :-)
-
Thanks. I asked here because it's not obvious that object.contains() is actually a LINQ extension. Sadly, you can't do what I want with object.contains(), which does not let you compare nested values directly. Turns out that what I need is
foo.Any(f => f.bar.data == "hello")
Which makes me a little sad, because
foo.Contains(nested value I was looking for)
would have been a lot simpler than having to break out my book and re-learn lambdas. Oh well, wave of the future :-)
How could
Contains()
have any "idea" in which properties offoo
to look for some value? For instance, should it look in all properties that are the same type as the value to find? What if it is nested arbitrarily deep? The only rational behavior is for the developer to be responsible to structure the query. Re: lambdas... they're not that hard! :) -
I cannot figure out the syntax for using the LINQ extensions on IList (and other interfaces) to search for values that are in nested objects. For instance, I have a List<foo>, where object foo contains two other objects, each of which have field "data". How do I use List.Contains<foo>("hello") to search for a foo object where foo.nestedobject.data = hello?
How would Contains know to look inside its member items? You can either use Any with a lambda as you've discovered, or you can implement equality checking on the class Foo and do
List.Contains(new Foo("hello"))
... if that makes any sense for the actual class you're using. I'd generally use the lambda, that makes it crystal clear what the test you're actually doing is.