2

我试图过滤掉一个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从主要业务对象中过滤掉

4

2 回答 2

4

取决于您是否希望任何子对象具有该属性或所有子对象都具有该属性:

var filteredList = listOfMainBusinessObject
                       .Where(x => x.ListOfSubobject.Any(s=>s.PropertyX));

或者

var filteredList = listOfMainBusinessObject
                      .Where(x => x.ListOfSubobject.All(s=>s.PropertyX));

此外,您还有一些似乎无效或不必要的演员表。要转换为 a MainBusinessObjectCollection(假设它是MainBusinessObjects 的集合),您可能必须从返回的 中初始化IEnumerableWhere

var newList = new MainBusinessObjectCollection(filteredList);
于 2012-10-16T14:05:39.570 回答
0

如果你想要Subobjects所有Subobject.PropertyX == true

listOfMainBusinessObject.SelectMany(x => x.ListOfSubobject)
                        .Where(x => x.PropertyX == true);
于 2012-10-16T14:09:16.747 回答