代码之家  ›  专栏  ›  技术社区  ›  Maciek

C#/LINQ/获取子集合中与条件匹配的所有元素?

  •  1
  • Maciek  · 技术社区  · 15 年前

    我有一个:

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

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

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

    1 回复  |  直到 7 年前
        1
  •  6
  •   Stan R.    15 年前
    var result = Items.Where( y => y.MyProperty );
    
    var biggerResult = x_collection.SelectMany( x => x.Items.Where( y => y.MyProperty ) );