我正在尝试过滤掉ObservableCollection<MainBusinessObject>
,我需要过滤集合中Subobject.PropertyX == true
的所有项目。
MainBusinessObject
- PropertyA int
- PropertyB string
- ListOfSubobject ObservableCollection<Subobject>
Subobject
- PropertyX bool
- PropertyY int
- PropertyZ - string
我真的想远离循环和if语句,但我似乎无法正确获取LinQ语句。这就是我到目前为止所做的:
return (MainBusinessObjectCollection)
listOfMainBusinessObject.Where(x =>
(x as MainBusinessObject).CanBePartitioned == true);
修改 我需要从主要业务对象
中过滤掉ListOfSubobject
答案 0 :(得分:4)
取决于您是否希望任何子对象具有该属性或所有子对象具有该属性:
var filteredList = listOfMainBusinessObject
.Where(x => x.ListOfSubobject.Any(s=>s.PropertyX));
或
var filteredList = listOfMainBusinessObject
.Where(x => x.ListOfSubobject.All(s=>s.PropertyX));
你也有一些看似无效或不必要的演员表。要转换为MainBusinessObjectCollection
(假设它是MainBusinessObject
s的集合),您可能必须从IEnumerable
返回Where
来初始化它:< / p>
var newList = new MainBusinessObjectCollection(filteredList);
答案 1 :(得分:0)
如果您希望所有Subobjects
与Subobject.PropertyX == true
:
listOfMainBusinessObject.SelectMany(x => x.ListOfSubobject)
.Where(x => x.PropertyX == true);