Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary ContainsKey and get value in one function

Tags:

c#

dictionary

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?

like image 949
iefpw Avatar asked Jun 30 '13 00:06

iefpw


People also ask

How to check key value in dictionary c#?

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.

Is ContainsKey case sensitive C#?

The key is handled in a case-insensitive manner; it is translated to lowercase before it is used.


2 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.

like image 117
Tom Studee Avatar answered Oct 19 '22 04:10

Tom Studee


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
like image 38
Simon Belanger Avatar answered Oct 19 '22 03:10

Simon Belanger