简体   繁体   中英

Dictionary ContainsKey and get value in one function

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?

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM