tags:

views:

281

answers:

1

I have an :

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

How do I create a LINQ query that will return an IEnumerable or ObservableCollection that will only get Y elements that have their MyProperty == true? I do realize it's probably a very easy question but I'm pretty confused with LINQ atm.

If possible I'd like to ask for a lamda-query - they're much easier for me to understand

+5  A: 
var result = Items.Where( y => y.MyProperty );

var biggerResult = x_collection.SelectMany( x => x.Items.Where( y => y.MyProperty ) );
Stan R.
Doesn't that return items from an X only? I need results from the whole x_collection?
Maciek
@Maciek, you didnt say that :)..edited answer.
Stan R.
Let me see if this works....
Maciek
Wow, that simple lol. I've noticed that when I'm casting trying to return the biggerResult as an ObservableCollection<Y> the query succeeds but the cast is null, any idea what might be wrong with that?ObservableCollection<Y> biggerResult = query as ObservableCollection<Y>;
Maciek
Please, don't compare to true! `y => y.MyProperty` will do just fine.
Trillian
that's because biggerResult is IEnumerable<Y>, so it cannot be upcasted to a more specific type.
Stan R.
Good point, I used this as an example, in my case I'm using a specific enum check heh.
Maciek
So basically, there's no way to return the query results as an ObservableCollection other then filling that collection manually from the IEnumerable<Y> ?
Maciek
@Maciek, correct.
Stan R.
To avoid manually populating the ObservableCollection, you can do: `new ObservableCollection<Y>(results.ToList())`
Joel Mueller