Best way to remove matching items from a list

In C #, when I want to remove some items from a list, I do it like this:

List<Item> itemsToBeRemoved = new List<Item>(); foreach(Item item in myList) { if (IsMatching(item)) itemsToBeRemoved.Add(item); } foreach(Item item in itemsToBeRemoved) { myList.Remove(item); } 

Is there a better way to do this?

+2
list c #
source share
7 answers

Well, you can call a method that does exactly what you want.

 myList.RemoveAll(IsMatching); 

Generally, it’s “better” to use a method that does exactly what you want, rather than reinventing it yourself.

+21
source share
 myList.RemoveAll(x=> IsMatching(x)); 
+12
source share

The use of Linq is slightly improved here.

 var itemsToRemove = myList.Where(item => IsMatching(item)).ToList(); foreach(Item item in itemsToBeRemoved) { myList.Remove(item); } 
+2
source share

How about returning your logic, adding elements that don't match, and just using a collection of results?

 List<Item> itemsTaken = new List<Item>(); foreach(Item item in myList) { if (!IsMatching(item)) itemsTaken.Add(item); } // use itemsTaken as if it were myList with items removed 
+1
source share

What I used is to create a reverse for loop:

 for (int i=myList.Count-1; i>=0; i--) { if (IsMatching(myList[i])) myList.RemoveAt(i); } 

But I'm sure there are more elegant ways to use LINQ.

+1
source share

Similar to what Jakers said, and assuming you are on .Net 3:

 myList = myList.Where(item => !IsMatching(item)).ToList(); 
0
source share
 foreach(Item singleItem in new List<Item>(allItems)) { if(IsMatching(singleItem)) allItems.Remove(singleItem); } 
0
source share

All Articles