Is there a way to call Dictionary<string, int>
once to find a value for a key? Right now I'm doing two calls like.
if(_dictionary.ContainsKey("key") {
int _value = _dictionary["key"];
}
I wanna do it like:
object _value = _dictionary["key"]
//but this one is throwing exception if there is no such key
I would want null if there is no such key or get the value with one call?
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.
You can use TryGetValue
int value;
bool exists = _dictionary.TryGetValue("key", out value);
TryGetValue
returns true if it contains the specified key, otherwise, false.
The selected answer the correct one. This is to provider user2535489 with the proper way to implement the idea he has:
public static class DictionaryExtensions
{
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue fallback = default(TValue))
{
TValue result;
return dictionary.TryGetValue(key, out result) ? result : fallback;
}
}
Which can then be used with:
Dictionary<string, int> aDictionary;
// Imagine this is not empty
var value = aDictionary.GetValue("TheKey"); // Returns 0 if the key isn't present
var valueFallback = aDictionary.GetValue("TheKey", 10); // Returns 10 if the key isn't present
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With