Question

So, my code stop running when a node is null, but i .

        Node node = nodeMap[x];  (BREAKS HERE case x isn't in the tree yet)
        if(node == null)
        {
            node = new Node();
            node.Equals(x);
            nodeMap.Add(x, node);
        }

ERROR: An unhandled exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in System.dll

Additional information: The key is not in the dictionary.

Was it helpful?

Solution 2

Use TryGetValue() method. If the node exists it'll retrieve it, if not it'll proceed to add the node to the dictionary. Whichever condition occurs it allows you to use the node object from there on.

Node node = null;
if(!nodeMap.TryGetValue(x, out node))
{
    node = new Node();
    node.Equals(x);
    nodeMap.Add(x, node);
}

OTHER TIPS

You are not clear on your question, but I presume you want your error to disapear;).Rather do

 Node node;
 if(!nodeMap.ContainsKey(x))
 {
   node = nodeMap[x];
   node = new Node();
   node.Equals(x);
   nodeMap.Add(x, node);
}else
  node = nodeMap[x]

Poof

Check whether x exists before trying to access it:

Node node = nodeMap.Where(y => y.Key == x).FirstOrDefault());
if (node == null)
{
    node = new Node();
    node.Equals(x);
    nodeMap.Add(x, node);
}

Hope this is useful ;)

As stated in documentation (http://msdn.microsoft.com/en-us/library/7w6691xh(v=vs.110).aspx)

If the specified key is not found, a get operation throws a KeyNotFoundException

So, nothing strange.

Use the ContainsKey method to check if it does exist. I presume you're adding it otherwise:

if(!nodeMap.ContainsKey(x))
{
    nodeMap.Add(x, new Node());
}

// now you're sure it does exist, as you added it
// above
Node node = nodeMap[x];

I removed your invocation of Equals. Under no account should Equals have side effects, and therefore the call should not be needed unless you work with the return value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top