LoginSignup
1
1

More than 5 years have passed since last update.

if文でDictionaryのContantsKeyと中身を同時に判定させた時の動きについて

Posted at

備忘録代わり

Diconaryの中身の存在を確認しつつ、その値を使って、bool型を返すメソッド等を同時に判定したいときに、下記の様に書けば出来る。

成功例:if文にて、ContainsKeyがtrueであり、dictonaryの中身を読み取れた結果を更に判定している

Dictionary<string, bool> dictionary = new Dictionary<string,bool>();
            dictionary.Add("a" , true);

            try
            {
                string key = "a";
                if (dictionary.ContainsKey(key) && dictionary[key])
                {// ここに行く
                    Console.Write("1");
                }
                else
                {
                    Console.Write("2");
                }
            }
            catch(Exception ex)
            {
                Console.Write("3");
            }

成功例:if文にて、ContainsKeyがfalseであり、dictonaryの中身を読み取る前に判定している

Dictionary<string, bool> dictionary = new Dictionary<string,bool>();
            dictionary.Add("a" , true);

            try
            {
                string key = "b";
                if (dictionary.ContainsKey(key) && dictionary[key])
                {
                    Console.Write("1");
                }
                else
                {// ここに行く
                    Console.Write("2");
                }
            }
            catch(Exception ex)
            {
                Console.Write("3");
            }

失敗例:if文の中で、ContainsKeyをDictionaryの中を見る処理より後に行っている為。

if文の複数判定時には、左辺から見ている様。

Dictionary<string, bool> dictionary = new Dictionary<string,bool>();
            dictionary.Add("b" , true);

            try
            {
                string key = "a";
                if (dictionary[key] && dictionary.ContainsKey(key))
                {
                    Console.Write("1");
                }
                else
                {
                    Console.Write("2");
                }
            }
            catch(Exception ex)
            {// ここに行く
                Console.Write("3");
            }
1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1