OdeToCode IC Logo

What’s Wrong With This Code? (#22)

Sunday, October 11, 2009

It’s a bug you’ve probably learned to avoid in .NET programming, it’s just not as obvious now.

var cities = new List<string>
{ 
    "Baltimore", 
    "Munich", 
    "Copenhagen" 
};

var citiesToRemove = 
    cities.Where(city => city.Length < 7);

foreach (var s in citiesToRemove)
{
    cities.Remove(s);
}
What goes wrong, and what’s an easy fix?

--

All links to my “What’s Wrong” series are here