Hashtables: Item has already been added

In my previous two posts about hashtables I provided examples for creating a hashtable, returning a specific value and a description around performance. This post will focus on the errors you should expect if you start using a hashtable.

The most common exception I see happens when the data I’m storing in the hashtable is not unique. For example, in the first post in the series we created a simple hashtable from a list of HTML colors. If my input list had the color ‘red’ listed on two different lines, I would have seen an error similar to this:

Add : Exception calling “Add” with “2” argument(s): “Item has already been added. Key in dictionary: ‘Red’ Key being
added: ‘Red'”
At line:1 char:17
+ $colorCodeHT.Add <<<< ('Red','123456') + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

This is an easy error message to generate if you want to see the actual error. Follow the examples in the first post and then try and re-add the color red using the following line:
[cc lang=”powershell”]
$colorCodeHT.Add(‘Red’,’123456′)
[/cc]

The hashtable object includes a .Contains method, which can be used in an if statement to prevent this exception from happening:
[cc lang=”powershell”]if ($colorCodeHT.Contains(‘Red’)) { “Color ‘red’ has already been added” } else { $colorCodeHT.Add(‘Red’,’123456′) }[/cc]

This statement checks for the presence of a ‘Red’ item and only attempts to add if a value does not already exist.

This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Notify me of followup comments via e-mail. You can also subscribe without commenting.