Allen Allen - 4 months ago 12
C# Question

Trying to Filter a collection using LINQ where the collection has a collection which also has a collection with a property that is nullable

Ok, this has been a pretty interesting problem for me to solve, so I will try and do my best to ask this in a way in which you can understand.

So, I have a collection of objects which contains a collection of objects which contains a collection of objects which has a property that sometimes can be null.

It looks something like this pseudocode:

Class ObjectA {
public IEnumberable<ObjectB>
}
Class ObjectB {
public IEnumberable<ObjectC>
}
Class ObjectC {
property? a;
}


Ok, now I basically need to filter out all of the ObjectC where the property = someValue or the property is null.

I tried this: (remember, this is just an example, not real code)

IEnumberable<ClassA> collection;
List<string> filters; // This contains a list of filters
collection = collection.Where(a => a.collectionB.All(b =>
b.collectionC.Where(c => !filter
.Contains(c.Property))?
.Count() == 0))
.ToList();


So, the problem is that if I match a filter to the
c.Property
nothing happens. It should remove that one from the
collection
but it isn't. I also need to not filter out any of the ones where the
c.Property == null
or the
collectionC == null
.

EDIT:
What I am really trying to accomplish is if some c.Property = 'x' and some c.Property = 'y' and some c.Property = null, I want to remove from my
collection
anything where c.Property = 'x' but leave the rest.

Answer
collection.Where(a=>a.collectionB.Any(b=> b.collectionC == null ||
   b.collectionC.Any(c=>c.Property == null || filters.Contains(c.Property))))
Comments