filtering observable collection

entity-framework-6 linq observablecollection wpf


Entity Framework 6 and LINQ are all new to me. I have a data grid that is tied to an ObservableCollection through a CollectionViewSource. Simply by according to the instructions in, I was able to add to, alter, and delete data from the grid. The tutorial demonstrates how to load a complete table, or category:

private void Window_Loaded(object sender, RoutedEventArgs e) 
     System.Windows.Data.CollectionViewSource categoryViewSource = 

     categoryViewSource.Source = _context.Categories.Local; 

Now, let me ask you a pretty straightforward question: What if I only want to load certain of the categories? The grid will only load those categories since I want some users to be able to update particular categories.

4/30/2015 7:57:56 AM

Accepted Answer

You must apply a filter.

categoryViewSource.View.Filter = item =>
                     Categories category = item as Categories; // hope this are your items
                     return category.Id > 10; // or put whatever condition you want

The aforementioned approach would only return categories with Ids greater than 10. (just used Id as an example).

Check out this link as well:

4/30/2015 9:01:39 AM

Popular Answer

You can try using linq in the following manner if you want to:

ObservableCollection<Model> collection = new ObservableCollection<Model>();

ObservableCollection<Model> filteredCollection = new ObservableCollection<Model>(from item in collection where item.ID >0 && item.ID < 10 orderby item.ID select item);

If I'm not mistaken, you may directly tie an observablecollection to a wpf datagrid's ItemsSource property.

I recommend reading if you want to learn more about linq.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow