RemoveAll for ObservableCollections?

前端 未结 7 1390
时光说笑
时光说笑 2020-12-02 21:39

I am looking for Linq way (like RemoveAll method for List) which can remove selected items from my ObservableCollection.

I am too new to create an extension method f

7条回答
  •  抹茶落季
    2020-12-02 22:21

    This is my version of an extension method solution, which is only a slight variation on the accepted answer, but has the advantage that the count returned is based on confirmed removal of the item from the collection:

    public static class ObservableCollectionExtensionMethods
    {
        /// 
        /// Extends ObservableCollection adding a RemoveAll method to remove elements based on a boolean condition function
        /// 
        /// The type contained by the collection
        /// The ObservableCollection
        /// A function that evaluates to true for elements that should be removed
        /// The number of elements removed
        public static int RemoveAll(this ObservableCollection observableCollection, Func condition)
        {
            // Find all elements satisfying the condition, i.e. that will be removed
            var toRemove = observableCollection
                .Where(condition)
                .ToList();
    
            // Remove the elements from the original collection, using the Count method to iterate through the list, 
            // incrementing the count whenever there's a successful removal
            return toRemove.Count(observableCollection.Remove);
        }
    }
    

提交回复
热议问题