Reputation: 2230
Im trying to filter out an ObservableCollection<MainBusinessObject>
where I need to filter all items in the collection that have Subobject.PropertyX == true
.
MainBusinessObject
- PropertyA int
- PropertyB string
- ListOfSubobject ObservableCollection<Subobject>
Subobject
- PropertyX bool
- PropertyY int
- PropertyZ - string
I really want to stay away from looping and if statements, but I can't seem to get the LinQ statements right. This is what I have so far:
return (MainBusinessObjectCollection)
listOfMainBusinessObject.Where(x =>
(x as MainBusinessObject).CanBePartitioned == true);
EDIT
I need to filter out the ListOfSubobject
from the main business object
Upvotes: 2
Views: 98
Reputation: 152634
Depending if you want ANY sub-object to have that property or ALL sub-object to have that property:
var filteredList = listOfMainBusinessObject
.Where(x => x.ListOfSubobject.Any(s=>s.PropertyX));
or
var filteredList = listOfMainBusinessObject
.Where(x => x.ListOfSubobject.All(s=>s.PropertyX));
Also you have some casts that seem to be either invalid or unnecessary. To convert to a MainBusinessObjectCollection
(assuming it is a collection of MainBusinessObject
s), you're likely going to have to initialize it from the IEnumerable
that Where
returns:
var newList = new MainBusinessObjectCollection(filteredList);
Upvotes: 4
Reputation: 3435
If you want all Subobjects
with Subobject.PropertyX == true
:
listOfMainBusinessObject.SelectMany(x => x.ListOfSubobject)
.Where(x => x.PropertyX == true);
Upvotes: 0