If the following code finds a match, we’ll find out it’s a no-no.
foreach (string s in list) { if (s == "two") list.Remove(s); }
In VS2005, the code creates this friendly little dialog.
C# 2.0 introduces generics, and with generics come predicates. A predicate returns true when an object meets a set of conditions, otherwise false. A method like List
list.RemoveAll( delegate(string s) { return s == "Two"; } );
Alternatively, you can keep your logic inside a named method.
static bool MatchTwoPredicate(string s) { if (s == "Two") return true; return false; } // and later . . . list.RemoveAll(MatchTwoPredicate);
I feel either technique is easier on the eyes when compared to STL and functors in C++. Then again, I should be sleeping right now instead of blogging.