What is the best way to remove a set from a collection, but still keep the items that were removed in a separate collection?
I have written an extension method that does that, but I think there must be a better way. Here is my function:
public static List<T> FindAndRemove<T>(this List<T> lst, Predicate<T> match)
{
List<T> ret = lst.FindAll(match);
lst.RemoveAll(match);
return ret;
}
And you would use it like this:
List<String> myList = new List<String>();
myList.Add("ABC");
myList.Add("DEF");
myList.Add("ABC");
List<String> removed = myList.FindAndRemove(x => x == "ABC");
// myList now contains 1 item (DEF)
// removed now contains 2 items (ABC, ABC)
I'm not 100% sure what goes on behind the scenes in the FindAll
and RemoveAll
methods, but I imagine a better way would be to somehow "transfer" items from one list to the other.