Removing N items from a list conditionally,
I was writing some ASP.NET control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.
RemoveAll method of the generic
List class does a good job, but removes all items that match the condition, specified by the predicate.
What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?
If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach:
int limit = 30; // Suppose you want to remove 30 items at most list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);
That’s the answer Removing N items from a list conditionally, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.
The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you