-1

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.

aurbano
  • 3,324
  • 1
  • 25
  • 39

5 Answers5

1

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

Murdock
  • 4,352
  • 3
  • 34
  • 63
0

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 ;)

Relax
  • 283
  • 2
  • 15
  • This will be painfully slow in a big map, because you're potentially interating over the whole map (`O(n)`), whereas an indexer could look an item up quicker (something like `O(log n)`). – Matthias Meid Apr 03 '14 at 14:46
  • There's really no reason to use a LINQ search as you can call the TryGet method. The TryGet is extremely optimized, even for large sets. – Samir Banjanovic Apr 23 '14 at 13:48
0

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);
}
Samir Banjanovic
  • 400
  • 1
  • 4
  • 16
  • Isn't there a `!` missing, like `if(!nodeMap.TryGetValue(x, out node))`? Elegant solution with `TryGetValue` in general though. – Matthias Meid Apr 03 '14 at 14:25
-1

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.

astef
  • 8,575
  • 4
  • 56
  • 95
-1

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.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79