|
-
March 18th, 2012, 07:03 AM
#4
Re: Need Help with Parser C#
 Originally Posted by dahrull
Ok thanks, that's just what I was looking for!
However I tried to use a Try and Catch method and i can't see why it isnt working
Code:
try
{
outputBx.Text = "" + d[inputBx.Text];
}
catch (Exception ex1)
{
outputBx.Text = "Not found";
}
Any help on this? or how i'd use a TryGetValue. I only ask to use this instead of the contains key method is because i've been told that TryGetValue is a lot more efficient than contains key for use with a dictionary.
I don't see anything wrong with that code - it should be doing what it looks like it will do. What exact problem are you having with it?
As for TryGetValue, it is more efficient in the case that you are asking for a lot of keys which aren't in the dictionary. This is because it effectively is the same as checking the key is present (i.e. ContainsKey) before indexing it (i.e. Item). It therefore prevents lots of KeyNotFoundExceptions being thrown in the indexing when the keys are not present.
So it would be more efficient than what you are doing here (i.e. the try/catch) if you keep asking for non-existent keys.
However, this really isn't going to be an issue for you as this is all running from a GUI anyway, meaning the rate-determining step will be the time it takes the user to click a button I'm not saying efficiency is not a concern in programming, but you shouldn't worry about it unless you find that your specific application is running too slowly for your purpose.
As to how you would use TryGetValue, it would be like this:
Code:
string outputString = null;
if (d.TryGetValue(inputBx.Text, out outputString)){
// We have found the string
outputBx.Text = outputString
} else {
// Haven't found it - do something else
}
It returns a boolean to indicate whether the key was found, and if it is the value is returned via an out parameter.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|