C# で複数の条件を持つ if ステートメント

Abdullahi Salawudeen 2023年1月30日 2022年8月23日
  1. C# での演算子の使用
  2. C# で複数の論理条件を持つ if ステートメントを使用する
  3. C# の 3 項条件演算子
C# で複数の条件を持つ if ステートメント

条件文は、プログラムの実行フローを制御するために使用され、条件が真であるかどうかに基づいて実行されます。C# には、if ステートメントと switch ステートメントの 2つの条件分岐ステートメントがあります。

この記事では、C# でステートメントを返すために複数の条件で if ステートメントを使用する方法を紹介します。詳細については、このリファレンスを参照してください。

C# での演算子の使用

演算子は、C# の変数と値に対してさまざまな操作を実行するために使用されます。演算子は、算術演算子、割り当て演算子、比較演算子、論理演算子の 4つのカテゴリに分類できます。

比較演算子を使用すると、C# で 2つの値を比較できます。C# には 6つの比較演算子があります。

< より小さい a < b
> より大きい a > b
== 等しい a == b
<= 以下または等しい a <= b
>= より大きいか等しい a >= b
!= と等しくない a != b

論理演算子には 3つの比較があります。

  1. 論理積 (&&)-2つの比較文が両方とも真であれば、真を返します。それ以外の場合は、false を返します。
  2. 論理和(||)-比較されたステートメントの一方または両方が true の場合、true を返します。比較された両方のステートメントが false の場合にのみ false を返します。
  3. 論理否定(!)-compare ステートメントまたは引数を否定します。結果が false の場合は true を返し、その逆の場合は true を返します。

論理演算子は、個別に使用することも、組み合わせて使用​​することもできます。

C# で複数の論理条件を持つ if ステートメントを使用する

コードスニペット:

using System;  

class demo
{
	public static void Main()
	{
    	string a = "Abdul", b = "Salawu", c = "Stranger", A2 = "Age";
        bool checkbox = true;
    	string columnname = "Abdullahi Salawudeen";

        if (columnname != a && columnname != b && columnname != c
  			&& (checkbox || columnname != A2))
		{
   			Console.WriteLine("Columnname is neither equal to a nor b nor c nor A2, but the check box is checked");
		}
        //the else statement is necessary to stop the program from executing infinitely
  		else{
        	Console.WriteLine("columnname is unknown and checkbox is false");
        }
	}
}

出力:

Columnname is neither equal to a nor b nor c nor A2, but the check box is checked

C# の 3 項条件演算子

条件演算子 ?:は、三項条件演算子とも呼ばれ、if ステートメントのように機能します。ブール式を評価し、2つの式のうちの 1つの結果を返します。

ブール式が true の場合、最初のステートメントが返されます(つまり、? の後のステートメント)。そうでない場合は、2 番目のステートメントが返されます(つまり、:の後のステートメント)。詳細については、このリファレンスを参照してください。

構文:

condition ? consequent : alternative;

以下は、複数の論理条件を持つ三項演算子を使用したコード例です。

using System;

class demo
{
	public static void Main()
	{
    	string a = "Abdul", b = "Salawu", c = "Stranger", A2 = "Age";
        bool checkbox = false;
    	string columnname = A2;
         string x =(columnname != a && columnname != b && columnname != c
  			&& (checkbox || columnname != A2)) ? "Columnname is neither equal to a nor b bor c nor A2 nor is the check box true" : "columnname is unknown and checkbox is false";
            Console.WriteLine(x);
	}
}

出力:

columnname is unknown and checkbox is false
Abdullahi Salawudeen avatar Abdullahi Salawudeen avatar

Abdullahi is a full-stack developer and technical writer with over 5 years of experience designing and implementing enterprise applications. He loves taking on new challenges and believes conceptual programming theories should be implemented in reality.

LinkedIn GitHub

関連記事 - Csharp Statement