I’ve been scouring multiple resources and can’t figure this one out; I am trying to filter an Array of objects based on a Property that is nested a couple levels deep. I’ve simplified things, so let’s say I have the following classes:
class A {
B[] bb;
}
class B
C[] cc;
}
class C {
string value;
}
And now the code:
A[] aa = ...;
A[] filteredAa = aa.Where(... //NEED HELP HERE
What I want to do is filter the aa array such that it gives me only those A elements that have at least one B element that have at least one C element has a value of “hello” (e.g. aa[0] would be included in the filteredAa array if aa[0].bb[3].cc[2].value = “hello”).
Can this type of filtering even be done? I think and hope this makes sense, but please let me know if I can clarify any further.
You need to use
Any– and it sounds like you need to use it twice:So working up from the inside:
Cobject is useful if its value is “hello”Bobject is useful if any of itsCvalues are usefulAobject is useful if any of itsBvalues are usefulWherefilters a sequence ofAobjects, leaving only the useful onesYou can use
ToArray()at the end if you really want an array, but I would typically useToListor just keep it as anIEnumerable<A>.