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
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/