This code comes from a videogame,i need to add various items of this type,but when i change locations in a new script duped,there is an existing key with same parameter,how can i change key value for each one?Thank you so much,Here is the important code from script:
`
protected Dictionary<Point3D, Map> ListOfLocations = new Dictionary<Point3D, Map>()
{
{ new Point3D(1185, 1838, 0), Map.Felucca },
{ new Point3D(1215, 1809, 0), Map.Felucca },
{ new Point3D(1215, 1839, 0), Map.Felucca },
{ new Point3D(1214, 1839, 0), Map.Trammel },
};
public Point3D GetRandomLocation()
{
return ListOfLocations.ElementAt(Utility.Random(0, ListOfLocations.Count)).Key;
}
`
CodePudding user response:
If the Point3D
is an object, not a struct, then modifying it wont change its reference value, which is used as an actual key in the dictionary in this case. Easiest way of changing a key in this case would be to remove key value pair and add a newly created one (newly created key and same value will work). For only changing the value it would not be necessary.
CodePudding user response:
Cannot insert same key in dictionary So I have written sample code that will help you.
what I got from your question is that Location is key of dictionary that is type of Point3D
Point3D location = your location;
if (!ListOfLocations.ContainsKey(location))
{
// then change in dictionary for location
}
else
{
Map map = ListOfLocations[location];
ListOfLocations.Remove(location);
// then change in dictionary for location as per your requirement
//for Example ListOfLocations.Add(location, newmap);
}
Algo :-
check key exist in dictionary(that use hashtable in background)
1.a if No then do needful.
1.b else remove existing key from dictionary then do needful.