Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause on collections within collections

Tags:

c#

linq

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?

like image 770
ca8msm Avatar asked Jan 18 '26 10:01

ca8msm


1 Answers

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"))));
like image 191
René Vogt Avatar answered Jan 20 '26 23:01

René Vogt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!