Remove all from ICollection - CSharp System.Collections

CSharp examples for System.Collections:ICollection

Description

Remove all from ICollection

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
using System.Linq;
using System.Collections.Generic;
using System;//from  w ww  .j  a va 2  s. c  o  m

public class Main{

        public static void RemoveAll<T>(this ICollection<T> collection, Func<T, bool> predicate)
        {
            if (collection is List<T>)
            {
                ((List<T>)collection).RemoveAll(predicate);
            }
            else if (collection is AbsCollection<T>)
            {
                ((AbsCollection<T>)collection).RemoveAll(predicate);
            }
            else
            {
                List<T> toRemove = new List<T>();
                foreach (T t in collection)
                {
                    if (predicate(t))
                    {
                        toRemove.Add(t);
                    }
                }
                RemoveAll(collection, toRemove);
            }
        }

        public static void RemoveAll<T>(this ICollection<T> collection, IEnumerable<T> enumer)
        {
            if (collection is AbsCollection<T>)
            {
                ((AbsCollection<T>)collection).RemoveAll(enumer);
            }
            else
            {
                foreach (T t in enumer)
                {
                    collection.Remove(t);
                }
            }
        }
}

Related Tutorials