17

If i have

IEnumberable<Car> list

and i want to remove an item from this list based on a property of the car

i want something like:

list.RemoveWhere(r=>r.Year > 2000)

does something like this exist ?

i am doing this over and over so i want to avoid copying the list each time to just remove one item

1
  • Is it a List<Car> or just an IEnumerable<Car>? Commented Jul 24, 2010 at 14:26

3 Answers 3

22

Very late to the party but for any one would comes across this problem, here is a cleaner solution:

MyList.RemoveAll( p => p.MyProperty == MyValue );
Sign up to request clarification or add additional context in comments.

1 Comment

This is a good solution, but IEnumerable<T> does not have this method. You will have to first ensure the collection is a List<T> type.
17

IEnumberable is immutable, but you can do something like this:

list = list.Where(r=>r.Year<=2000)

or write an extension method:

public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> query, Predicate<T> predicate)
{ 
    return query.Where(e => !predicate(e));
}

1 Comment

@ooo IEnumerable is immutable, so you can't simple add or remove items, it's impossible. Of course you could just use a List, but it is not possible to say if this would be faster. If you do this over and over, keep the deferred execution in mind.
4

If you are working with IEnumerable<T>, how about Where?

list = list.Where(car => car.Year <= 2000);

If you are working with ICollection<T> and you not just get a filtered result but really intend to manipulate the source collection, you can create an own tailor made extension for collection:

  public static class CollectionExtensions {
     public static ICollection<T> RemoveWhere<T>(this ICollection<T> collection, Func<T, bool> predicate) {
        List<T> toRemove = collection.Where(item => predicate(item)).ToList();
        toRemove.ForEach(item => collection.Remove(item));
        return collection;
     }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.