What happens to C# Dictionary lookup if the k

2020-05-18 04:14发布

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?

标签: c# dictionary
9条回答
▲ chillily
2楼-- · 2020-05-18 04:40

Assuming you want to get the value if the key does exist, use Dictionary<TKey, TValue>.TryGetValue:

int value;
if (dictionary.TryGetValue(key, out value))
{
    // Key was in dictionary; "value" contains corresponding value
} 
else 
{
    // Key wasn't in dictionary; "value" is now 0
}

(Using ContainsKey and then the the indexer makes it look the key up twice, which is pretty pointless.)

Note that even if you were using reference types, checking for null wouldn't work - the indexer for Dictionary<,> will throw an exception if you request a missing key, rather than returning null. (This is a big difference between Dictionary<,> and Hashtable.)

查看更多
一纸荒年 Trace。
3楼-- · 2020-05-18 04:40
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

查看更多
Emotional °昔
4楼-- · 2020-05-18 04:42

You should probably use:

if(myDictionary.ContainsKey(someInt))
{
  // do something
}

The reason why you can't check for null is that the key here is a value type.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-05-18 04:43

ContainsKey is what you're looking for.

查看更多
Fickle 薄情
6楼-- · 2020-05-18 04:49

A helper class is handy:

public static class DictionaryHelper
{
    public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
    {
        TVal val;
        if( dictionary.TryGetValue(key, out val) )
        {
            return val;
        }
        return defaultVal;
    }
}
查看更多
萌系小妹纸
7楼-- · 2020-05-18 04:50

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}
查看更多
登录 后发表回答