Common IssueIf you try and alter a collection from within a foreach loop then it will throw and exception ( and quite rightly so).
What NOT TO DOAlthough this will work it is not very good code. Can you spot the issues ?? (answers below)
- You iterate through the entire collection even of the search item is the first item there.
- It will be slow for large collections
- Other developers will laugh at you (or shake their head and mutter in despair)
Easy MethodA must more efficient method is pull the item you want to remove via a Find on the collection and
In the above code you might think that it will throw an exception if there is no search results, but List.Remove(null) does not throw an exception.