30

I have a ListCollectionView which has had a filter applied to it. In order to get the filtered items from the list (e.g. to write to a file), is there a clean way of doing it.

My current solution is

var filteredItems = originalCollection.Where(i => view.Filter(i));

In the code I do check for nulls on originalCollection and view.Filter.

Is there a cleaner way of doing this?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
John Oxley
  • 14,698
  • 18
  • 53
  • 78

2 Answers2

51

The GetEnumerator method takes the filter into account, so you can just foreach over the view:

ICollectionView view = ...
view.Filter = ...

foreach(Foo o in view)
{
    ...
}

(assuming the objects in the original collection are of type Foo).

You can also use the Cast extension method:

var filteredItems = view.Cast<Foo>();
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • ICollectionView view = ... Please show a full example. I have filtered items in a DataGrid and the view i get from GetDefualtView How do i get the "CurrentView" ? – eran otzap Jun 28 '20 at 09:27
0

Here is full example how to get filtrated items from DataGrid:

ICollectionView view = CollectionViewSource.GetDefaultView(*yourDataGrid*);
foreach(Foo o in view)
{
  ...
}
XavrasX
  • 41
  • 2