Reputation: 7042
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?
Upvotes: 9
Views: 14744
Reputation: 8656
I suppose, you could do something like this (or write a much clearer extension method).
object _value = _dictionary.ContainsKey(myString) ? _dictionary[myString] : (int?)null;
I'm not sure I'd be particularly happy using that though, by combining the null and your "Found" condition, I would have thought you're just shifting the problem to a null check slightly further down the line.
Upvotes: 0
Reputation: 4542
this should probably do it,for your purposes. Like you asked in the question ,getting all in one go,null or the value,into an object:
object obj = _dictionary.ContainsKey("key") ? _dictionary["key"] as object : null;
or..
int? result = _dictionary.ContainsKey("key") ? _dictionary["key"] : (int?)null;
Upvotes: 1
Reputation: 14870
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
Upvotes: 9
Reputation: 10452
You can use TryGetValue
int value;
bool exists = _dictionary.TryGetValue("key", out value);
TryGetValue
returns true if it contains the specified key, otherwise, false.
Upvotes: 12