myGenericList.RemoveAll(x => (x.StudentName == "bad student"));
Works great, but a bindinglist does not have this method. How can I create an extension method for the bindinglist that takes as input a predicate and does the magic like the canned removeall for List
thankyou
Like I said in a comment, there is no magic in extension methods, just write the code the same way as if you wrote it normally, just put it in a static method in a static class and use the
thiskeyword:You have to use
ToArray()(orToList()), becauseWhere()is lazy and only enumerates the collection when needed and you can’t enumerate changing collection.Although this solution is quite slow (O(N2)), because every
Remove()has to look through the collection to find the correct item to remove. We can do better:This uses the fact that we can get to i-th item in constant time, so the whole method is O(N). The iteration is easier to write backwards, so that indexes of items we have yet to consider aren’t changing.
EDIT: Actually the second solution is still O(N2), because every
RemoveAt()has to move all the items after the one that was removed.