RemoveAll for ObservableCollections?
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);
Iterating backwards should be more efficient than creating a temporary collection as in Daniel Hilgarth's example.
public static class ObservableCollectionExtensions
{
public static void RemoveAll<T>(this ObservableCollection<T> collection,
Func<T, bool> condition)
{
for (int i = collection.Count - 1; i >= 0; i--)
{
if (condition(collection[i]))
{
collection.RemoveAt(i);
}
}
}
}