I have a node class which is contained in a SortedDictionary:
SortedDictionary<Node, bool> openList = new SortedDictionary<Node, bool>();
I need to write the CompareTo method on the node, so that the nodes are sorted from lowest to highest based on an int value(F). I also need to be able to check if a node already exists in the dictionary based on their position (this position is what makes the node Unique). The CompareTo looks like this:
public int CompareTo(Node other)
{
if (GridPosition != other.GridPosition)
{
if (F > other.F)
{
return 1;
}
if (F < other.F)
{
return -1;
}
return -1;
}
return 0;
}
The problem is, that it doesn't always return the correct result. For example, the following line of code will return false even though the node is in the dictionary. However it sorts all the nodes that I add to the dictionary exactly as I want it.
Node node = new Node(); //It has a grid position and a f value
openList.add(node, false);
if(openList.Keys.Contains(node)) //this returns false
{
}
To fix this I created an EqualityComparer and used it while comparing the values. The equality comparer looks like this:
class NodeEqualityComparer : IEqualityComparer<Node>
{
public bool Equals(Node x, Node y)
{
return x.GridPosition == y.GridPosition;
}
public int GetHashCode(Node obj)
{
return obj.GridPosition.GetHashCode();
}
}
I'm using this equality comparer as a parameter in the Contains method on the SortedDictionary, this works fine and it returns the correct result based on the content in the Dictionary:
if (openList.Keys.Contains(currentNode,new NodeEqualityComparer())) //This will return true if the node is in the dictionary
{
}
The problem occours when I need to remove a node from the Dictionary. The remove function is using the CompareTo method on the Node to find the node to remove, and as I stated earlier, this function appreantly doesn't return the correct result when comparing the objects. This means that the code below will not remove the node from the dictionary 100% of the time. You can't pass an equalityComparer to the remove function, so that can't fix my problem.
Node node = new Node(); //It has a grid position and a f value
openList.add(node, false);
openList.Remove(node);
Maybe I'm handeling this in a wrong way, so if anyone have some suggestions for solving this problem I'll be very happy to hear them. Maybe I can write a CompareTo function that solves the problem?