Skip to main content
 首页 » 编程设计

C#/LINQ/获取符合条件的子集合的所有元素

2024年01月29日28mfryf

我有一个:

ObservableCollection<X> x_collection = new ObservableCollection(); 
 
public class X 
{ 
    public X()  
    {  
         Items = new ObservableCollection<Y>(); 
         for(int i = 0; i < 10; i++) 
         { 
 
             Items.Add(new Y(i % 2 == 0)); 
         } 
    } 
    public ObservableCollection<Y> Items {get; set;} 
} 
 
public class Y 
{ 
    public Y() : this(true) {} 
    public Y(bool y) { MyProperty = y; } 
    public bool MyProperty { get; set; } 
} 

如何创建将返回 IEnumerable 或 ObservableCollection 的 LINQ 查询,该查询将仅获取具有 MyProperty == true 的 Y 元素?我确实意识到这可能是一个非常简单的问题,但我对 LINQ atm 很困惑。

如果可能的话,我想请求一个 lambda 查询——它们对我来说更容易理解

请您参考如下方法:

var result = Items.Where( y => y.MyProperty ); 
 
var biggerResult = x_collection.SelectMany( x => x.Items.Where( y => y.MyProperty ) );