I got an ObservableCollection (Zone class contains a IsFiltered boolean property) on which several items got theirs IsFiltered property set to true. For a few cases, I need to unilateraly remove all filters (i.e. set IsFiltered prop to false for all ObservableCollection items).

Is there a way to achieve this the way ObservableCollection.Single(LINQ request) do it, or do I have to loop on my ObservableCollection to set this prop to false on all items?

Thanks for your answer !

有帮助吗?

解决方案

You'll have to loop but at least restrict your loop to the objects that need resetting:

foreach(var zone in zones.Where(z => z.IsFiltered))
{
     zone.IsFiltered = false;
}

As other answers/comments have mentioned, avoid Linq for the update. See Jon Skeet's answer https://stackoverflow.com/a/1160989/1202600 - Linq is for querying, not updating.

其他提示

I am not sure if this is what you are looking for, but Lists in C# got ForEach method which kind of does what you want, so:

myObservableCollection.ToList().ForEach(x => x.MyFlag = false);

Posting my thoughts (since you haven't accepted any answer as yet - please consider if you have moved on)

There is no other way than iterating through 'ObservableCollection'. You may find APIs (linq) to do that for you, but in the end it has to iterate through all objects to update their state.

If your collection is updated by other threads then you need to consider thread safety also (it will through exception if other thread updates while you are iterating to update IsFiltered)

Other point is updating a property doesn't reflect in binded UI unless that property raises 'NotifyPropertyChanged' event. So your object should have something like below:

public bool IsFiltered{
get { return _isFiltered; }
set {
    if (_isFiltered == value) return; //no need to modify and trigger UI update
    _isFiltered = value;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top