Dictionary ContainsKey and gets the value in one function

Is there a way to call Dictionary<string, int> once to find the value for the key? Right now I'm making two calls like.

 if(_dictionary.ContainsKey("key") { int _value = _dictionary["key"]; } 

I want to do it like:

 object _value = _dictionary["key"] //but this one is throwing exception if there is no such key 

I would like to null if there is no such key or get the value with a single call?

+6
source share
4 answers

You can use TryGetValue

 int value; bool exists = _dictionary.TryGetValue("key", out value); 

TryGetValue returns true if it contains the specified key, otherwise false.

+9
source

The selected answer is correct. This is for user2535489 provider with the correct way to implement the idea that it 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 
+7
source

this should probably do it, for your purposes. Just as you asked a question by adding everything to one end, zero or a value, in an object:

 object obj = _dictionary.ContainsKey("key") ? _dictionary["key"] as object : null; 

or..

 int? result = _dictionary.ContainsKey("key") ? _dictionary["key"] : (int?)null; 
+1
source

I suppose you could do something like this (or write a more understandable extension method).

  object _value = _dictionary.ContainsKey(myString) ? _dictionary[myString] : (int?)null; 

I'm not sure that I would be particularly pleased to use this, although by combining the null and your condition "Found", I would think that you just shift the problem to the null check a little further down the line.

0
source

Source: https://habr.com/ru/post/948402/


All Articles