Friday, August 27, 2010

How to remove items from Collection using lambda expression

Usefull extension method which allows removal of all items in ObservableCollection based on lambda expression.

It can be modified for any type of collection which allows access to items using indexer (including arrays).

public static class ObservableCollectionExtensions
    {
        public static void RemoveAll(this ObservableCollection items, Func match)
        {
            for (int i = items.Count - 1; i >= 0; i--)
            {
                if (match(items[i]))
                {
                    items.RemoveAt(i);
                }
            }
        }
    }

Now you can easily remove any items from collection by calling:
collection.RemoveAll(ii => ii.State == ObjectState.Deleted);