Please compare these two codes. I can't understand why former one didn't work while latter one work perfectly.
// With loop - not work
for (int i = 0; i < 5; i++)
{
Location l = new Location();
l.Identifier = i.ToString();
_locations.Add(l);
}
////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0; //raised Key not exists error
Here is working version...
// Without Loop - it work
Location l1 = new Location();
l1.Identifier = "1";
_locations.Add(l1);
Location l2 = new Location();
l2.Identifier = "2";
_locations.Add(l2);
Location l3 = new Location();
l3.Identifier = "3";
_locations.Add(l3);
/////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0;
Any ideas? Thanks.
Edit: Location Class
public class Location
{
string _identifier;
public Location()
{
}
public string Identifier
{
get { return this._identifier; }
set { this._identifier=value; }
}
public override string ToString()
{
return _identifier;
}
}