2015-10-31 42 views
3

我有一個名爲mainList的列表。 mainList中的每個項目都包含另一個名爲detailList的列表。
我想從mainList中detailList中的屬性評估爲true的項目中選擇項目。C#Linq列表中的列表

我希望將工作:

var list = mainList.Where(x => x.detailList.Where(y => y.property == true)); 

這是不行的,它不能轉換detailList爲bool。

所以我的問題是如何選擇mainList中的項目,其中該項目在他的detailList中有一個有效的屬性。

回答

8

如果所有項目必須是真實的:

var list = mainList.Where(x => x.detailList.All(y => y.property)); 

如果ATLEAST一個

var list = mainList.Where(x => x.detailList.Any(y => y.property)); 
1

試試這個,如果列表中的「任何」項符合條件,任何將返回True。

var list = mainList.Where(x => x.detailList.Any(y => y.property == true)); 
0

得到答覆,但這裏有一個工作示例:

void Main() 
{ 
    var foo_list = new List<Foo>(); 
    foo_list.Add(new Foo(){InnerList = new List<Bar> { 
     new Bar{Pro=true, Ind =1}, 
     new Bar{Pro=true, Ind =2}, 
     new Bar{Pro=false, Ind =3} 
    }}); 
    foo_list.Add(new Foo(){InnerList = new List<Bar> { 
     new Bar{Pro=false, Ind =4}, 
     new Bar{Pro=false, Ind =5}, 
     new Bar{Pro=false, Ind =6} 
    }}); 

    var l = from x in foo_list 
      where x.InnerList.Any(b => b.Pro) 
      select x; 
    l.Dump(); 
} 

// Define other methods and classes here 
class Foo{ 
    public List<Bar> InnerList {get;set;} 
    public Foo() { 
     InnerList = new List<Bar>(); 
    } 
} 

class Bar { 
    public bool Pro { get; set; } 
    public int Ind { get; set; } 
} 

結果將持有第一個Foo,因爲它的一些Bar的財產Pro這是真的