I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the KeyNotFoundException
right where it occurs, and absorb it. All other exceptions will propagate to the top. Is this the best way to handle this? Or should I use a different lookup? The dictionary uses an int as its key, and a custom class as its value.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Try using: Dict.ContainsKey
Edit:
Performance wise i think
Dictionary.TryGetValue
is better as some other suggested but i don't like to use Out when i don't have to so in my opinion ContainsKey is more readable but requires more lines of code if you need the value also.I know this is an old thread but in case it's helpful the prior answers are great, but the comments of complexity and concerns of littering the code (all valid for me also) can be addressed.
I use a custom extension method to wrap up the complexity of the above answers in a more elegant form so that it's not littered throughout the code, and it then enables great support for null coalesce operator . . . while also maximizing performance (via above answers).
Then you can use it simply by importing the namespace System.Collections.Generic.CustomExtensions
One line solution using
TryGetValue
Be aware that value variable must be of type which dictionary returns in this case string. Here you can not use var for variable declaration.
If you are using C# 7, in which case you CAN include the var and define it inline:
Use
Dictionary.TryGetValue
instead:Here is a one line solution (Keep in mind this makes the lookup twice. See below for the tryGetValue version of this which should be used in long-running loops.)
Yet I find myself having to do this everytime I access a dictionary. I would prefer it return null so I can just write:
you should use the 'ContainsKey(string key)' method of the Dictionary to check if a key exists. using exceptions for normal program flow is not considered a good practice.