Reputation: 329
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.
Upvotes: 2
Views: 6996
Reputation: 309
filteredAa = aa.Where(x => x.bb.Any(y => y.cc.Any(z => z.value == "hello")))
Upvotes: 0
Reputation: 1499800
You need to use Any
- and it sounds like you need to use it twice:
var query = aa.Where(a => a.bb.Any(b => b.cc.Any(c => c.value == "hello")));
So working up from the inside:
C
object is useful if its value is "hello"B
object is useful if any of its C
values are usefulA
object is useful if any of its B
values are usefulWhere
filters a sequence of A
objects, leaving only the useful onesYou can use ToArray()
at the end if you really want an array, but I would typically use ToList
or just keep it as an IEnumerable<A>
.
Upvotes: 4
Reputation: 203802
If you are looking for where Value
is a specific value:
var result = aa.Where(a=>a.bb.Any(b => b.cc.Any(c => c.Value == "hello"));
If you just want to get all of those that have any value:
var result = aa.Where(a=>a.bb.Any(b => b.cc.Any(c => !string.IsNullOrEmpty(c.Value)));
Upvotes: 0
Reputation: 168958
Try this:
A[] filteredAa = aa.Where(a => a.bb.Any(b => b.cc.Any(c => c.value == "hello"))).ToArray();
Upvotes: 1