Reputation: 4125
In order to filter an list of objects I've defined this property:
private ICollectionView _view;
public ICollectionView View
{
get
{
return _view;
}
set
{
_view = value;
OnPropertyChanged("View");
}
}
And then my filter:
item.View = CollectionViewSource.GetDefaultView(item.myList);
item.View.Filter = delegate(object o)
{
if (myCondition)
{
return true;
}
}
The filter works fine but as ICollectionView is an interface I can't work with my items: if I call them this way:
element1 = item.View[0].SomeProperty;
I recieve
Cannot apply indexing with [] to an expression of type 'System.ComponentModel.ICollectionView'
I've tried to set in the beginning View
not as interface but later I couldn't make the filter work.
Doing so and trying to cast:
item.View = (ICollectionView)CollectionViewSource.GetDefaultView(item.myList);
Haven't brought me good results either.
What can I do in order not only to filter (in my case I display the items in a ComboBox) but also work with them... My aim is to be able to make a foreach loop for all elements remaining in the ComboBox. Is this possible?
Upvotes: 0
Views: 72
Reputation: 1929
Given List and ICollectionView:
List<SomeType> list;
ICollectionView view=CollectionViewSourse.GetDefaultView(list);
view.Filter=filter;
You can use
var filteredList=view.Cast<SomeType>().ToList();
to enable indexer for filtered collection. The list will change with the collection view. Therefore in some way it is not deterministic. I am not sure but quite interested to know what is your use case to force you to use indexer on collection view.
Upvotes: 0
Reputation: 8706
Store the view separately from the list. Shorthand below, fill in with appropiate INotifyPropertyChanged and such.
List<SomeType> list;
ICollectionView view;
view = list as ICollectionView;
view.Filter = obj => obj.someprop == somevalue;
list[ 10 ].someprop = somevalue
Upvotes: 1