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?
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.
myList.RemoveAll(x=> IsMatching(x));
The use of Linq is slightly improved here.
var itemsToRemove = myList.Where(item => IsMatching(item)).ToList(); foreach(Item item in itemsToBeRemoved) { myList.Remove(item); }
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
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.
Similar to what Jakers said, and assuming you are on .Net 3:
myList = myList.Where(item => !IsMatching(item)).ToList();
foreach(Item singleItem in new List<Item>(allItems)) { if(IsMatching(singleItem)) allItems.Remove(singleItem); }