RemoveAll for ObservableCollections?

Arpit Khandelwal picture Arpit Khandelwal · Feb 25, 2011 · Viewed 41.5k times · Source

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 for myself. Is there any way I remove items from ObservableCollection passing a Lambda expression?

Answer

Daniel Hilgarth picture Daniel Hilgarth · Feb 25, 2011

I am not aware of a way to remove only the selected items. But creating an extension method is straight forward:

public static class ExtensionMethods
{
    public static int Remove<T>(
        this ObservableCollection<T> coll, Func<T, bool> condition)
    {
        var itemsToRemove = coll.Where(condition).ToList();

        foreach (var itemToRemove in itemsToRemove)
        {
            coll.Remove(itemToRemove);
        }

        return itemsToRemove.Count;
    }
}

This removes all items from the ObservableCollection that match the condition. You can call it like that:

var c = new ObservableCollection<SelectableItem>();
c.Remove(x => x.IsSelected);