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

Posted by K. Scott Allen on Oct 11, 2009 in - Dotnet  | View Original Article |

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

Reply

Copyright © 2010 Answer My Query All rights reserved. Maintained by Orange Brains .