2012-10-16 120 views
2

我試圖過濾出ObservableCollection<MainBusinessObject>,我需要過濾集合中所有具有Subobject.PropertyX == true的項目。LinQ過濾聲明

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); 

編輯 我需要從主要業務對象

+1

您的意思是,如果'ListOfSubobject'中的_any_項目具有'PropertyX == true'來完全忽略該MainBusinessObject? –

+0

Where()的返回類型是IEnumerable 。你不能簡單地將它轉換爲MainBusinessObjectCollection。 – Ondra

+0

@Ondra這是我目前正在處理的問題。有沒有其他的方法呢? –

回答

4

根據篩選出ListOfSubobject,如果你想要的任何子對象有屬性或所有子-object有該屬性:

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

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

你也有一些演員似乎無效或不必要。要轉換爲MainBusinessObjectCollection(假設它是MainBusinessObject個集合),你很可能將不得不從IEnumerableWhere回報初始化:如果你希望所有SubobjectsSubobject.PropertyX == true

var newList = new MainBusinessObjectCollection(filteredList); 
0

listOfMainBusinessObject.SelectMany(x => x.ListOfSubobject) 
         .Where(x => x.PropertyX == true);