Best way to remove items from a collection

前端 未结 15 2030
天命终不由人
天命终不由人 2020-12-08 05:47

What is the best way to approach removing items from a collection in C#, once the item is known, but not it\'s index. This is one way to do it, but it seems inelegant at be

15条回答
  •  独厮守ぢ
    2020-12-08 06:46

    If it's an ICollection then you won't have a RemoveAll method. Here's an extension method that will do it:

        public static void RemoveAll(this ICollection source, 
                                        Func predicate)
        {
            if (source == null)
                throw new ArgumentNullException("source", "source is null.");
    
            if (predicate == null)
                throw new ArgumentNullException("predicate", "predicate is null.");
    
            source.Where(predicate).ToList().ForEach(e => source.Remove(e));
        }
    

    Based on: http://phejndorf.wordpress.com/2011/03/09/a-removeall-extension-for-the-collection-class/

提交回复
热议问题