-1

I'm stuck on something probably easy but I can't find how to solve that So It's the first time I used the dictionnary and in my code I have declared my variable:

Private Dictionary<string, bool> g_objDictionnary =new Dictionary<string, bool>();

and In my code I'd like to do something like:

If my g_objDictionnary bool for this key is true so do that. Which function have to use to do that?

Thanks for your help

3 Answers3

4

For an one liner to check if the key exists and get its value if so, you can do something like this:

if (g_objDictionnary.TryGetValue("some_key", out var value) && value) {
   // Do something
}

Edit
As HimBromBeere stated in the comments this syntax will only work for C#7 and higher. If you are using a version of C# below 7 you have to declare value beforehand:

bool value;
if (g_objDictionnary.TryGetValue("some_key", out value) && value) {
   // Do something
}
croxy
  • 4,082
  • 9
  • 28
  • 46
2
if(g_objDictionnary.ContainsKey(yourKey))
 if(g_objDictionnary[yourKey] == true)
 {
 }
aozk
  • 366
  • 5
  • 17
0

Since it's already a bool, you can just this:

if (g_objDictionnary["some_key"]) {
    // Go!
}

This assumes the key already exists in your dictionary.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66