Jesus Rodriguez
Jesus Rodriguez

Reputation: 12018

Querying multiple properties of List items

I have a List kind of:

List<Concept>
  --- Property
  --- List<Class2>
  --- --- Class2pty
  --- --- Class2pty2
  --- List<Class3>
  --- --- Class3pty

Having a querystring, I need a new List of Concepts that have that querystring on any property (well, a sort of properties), like Property or Class2pty2, Class3pty...

With Where I can query Property but I don't know how to query Class2pty and if it match, return the Concept that have that Class2

So, Can I do that with a single nested query or what can I do?

EDIT: Since I wasn't clear, I give an example

Imagine I have a querystring of "foo" and I have a List with this 4 items

Concept
  --- Property = "foo"
  --- List<Class2>
  --- --- Class2pty
  --- --- Class2pty2
  --- List<Class3>
  --- --- Class3pty

Concept
  --- Property
  --- List<Class2>
  --- --- Class2pty = "foo"
  --- --- Class2pty2
  --- List<Class3>
  --- --- Class3pty

Concept
  --- Property
  --- List<Class2>
  --- --- Class2pty = "bar"
  --- --- Class2pty2
  --- List<Class3>
  --- --- Class3pty

Concept
  --- Property
  --- List<Class2>
  --- --- Class2pty
  --- --- Class2pty2
  --- List<Class3>
  --- --- Class3pty = "foo"

First list item have foo on Property, on second item (imagine that List< Class2 > have like 10 instances of Class2 and one of them (or maybe more)) have foo on Class2Pty, the third item doesn't have foo on any property (in the Concept instance itself and inner instances), four item does have it.

So when any Concept item (incluiding their childs) have a property with that foo item, return the Concept item. In our case, 1, 2 and 4.

In short, having a list of concepts with inner lists, return every Concept that have a property with that string or if one of their child instances have it.

Upvotes: 1

Views: 1190

Answers (1)

Steve Py
Steve Py

Reputation: 35093

If I understand your question correctly, you want to select outer classes that match a condition, and contain an inner class that matches conditions?

testConcepts.Where( c => c.Property == "SomeValue" 
                         && c.Classes.Any(cls => cls.Class2Pty > 1) );

If the Concept does not have a matching property it is eliminated. The Concepts matching the property will be returned if they contain classes that match the expected criteria. (in my example, contain a property with a value > 1, can be any condition.)

To return the child classes that match from containers that match on their property, .SelectMany() can be used:

testClasses = testConcepts.Where( c => c.Property == "SomeValue")
                       .SelectMany( c => c.Classes ).Where( cls => cls.Class2Pty > 1 );

Upvotes: 1

Related Questions