ca8msm ca8msm - 2 years ago 62
C# Question

Where clause on collections within collections

Say you have a class which has a collections type property, and these also have the same structure within them e.g.

public class Test
{
String Name;
ICollection<Test2> Items;
}

public class Test2
{
String Name;
ICollection<Test3> Items;
}

public class Test3
{
String Name;
ICollection<Test4> Items;
}

public class Test4
{
String Name;
}


If I was looking for all Test classes where the Name equals a particular value I know I could do:

.Where(t => t.Name == "MyValue")


But, if I wanted to search on the Test4.Name property, how do you search for all instances of Test where Test4 equals a particular value?

Answer Source

You need to "nest" the queries:

List<Test> tests = ...
var result = tests.Where(
               t => t.Items.Any(
                 t2 => t2.Items.Any(
                   t3 => t3.Items.Any(t4 => t4.Name == "MyValue"))));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download