2012-12-11 38 views
3

我有一个ObservableCollection,其中包含另一个ObservableCollection。LINQ:获取列表中的所有项目

ObservableCollection<MyModel> models = new ObservableCollection<MyModel>(); 

我的模型看起来像这样:

public class MyModel 
{ 
    public ObservableCollection<MyModel2> list2 { get; set; } 
    public string Property1 { get; set; } 
} 

public class MyModel2 
{ 
    public string Property2 { get; set; } 
    public string Property3 { get; set; } 
} 

现在我想找到模型中的所有MyModel2项目其中 “Property2” == “测试1” 和 “Property3” == “test2的”

我知道如何在一个列表2中搜索以找到正确的项目,但我想搜索模型集合中的所有“list2”。

var result = from mod 
      in list2 
      where mod.Property2 == "test1" && mod.Property3 == "test2" 
      select mod; 

任何帮助将不胜感激。

回答

4

这听起来像你想要的东西,如:

var query = from model in models 
      from model2 in model.list2 
      where model2.Property2 == "test1" && model2.Property == "test2" 
      select model2; 

或非查询表达式形式:

var query = models.SelectMany(model => model.list2) 
        .Where(model2 => model2.Property2 == "test1" 
            && model2.Property == "test2"); 
+0

'.Select' =>'.SelectMany'? – Rawling

+0

@Rawling:是的,呃。 –

+0

再次感谢乔恩。 – user1011394

1
var result = 
    models.SelectMany(item => item.list2.Where(model => model.Property2 == "test1" && model.Property3 == "test2")); 
相关问题