私が作成したい比較の用語がわかりません:
if(test1 == true && test2 == true || test2 == true && test3 == true || test3 == true && test4 == true...)
{
//Do stuff
}
これを達成するための効果的な方法/機能はありますか? そうしないと、非常に長い if ステートメントが必要になります。どんな助けでも大歓迎です。
部位を指定する必要はありません==true
。以下のように書ける。
if(test1 && test2 || test2 && test3 || test3 && test4...)
{
//Do stuff
}
式自体を単純化したい場合は、ブール代数とブール式の簡約を調べることをお勧めします。
これは の形の表現ですAB + BC + CD + ...
。実行できる 1 つの削減は次のとおりです。
AB + BC = B(A+C) = B && (A || C)
リストを使用してすべての異なるブール値を格納することもでき、それらの 1 回の反復を使用してこれを計算できます。これにより、読みやすさが向上しますが、パフォーマンス/メモリのフットプリントはほとんど変わらないか、わずかに低下します。
var tests = new[] { test1, test2, test3, test4, ... };
for (int i = 0; i < tests.Length - 1; ++i) {
if (tests[i] && tests[i + 1]) {
// Do stuff
break;
}
}
または、bool をリストに入れることができれば、LINQ.ANY に変換されます。
List<bool> booList = new List<bool> { true, true, true, true };
bool isTrue = booList.Any(b => b);
Console.WriteLine(isTrue.ToString());
booList = new List<bool> { true, true, false, false };
isTrue = booList.Any(b => b);
Console.WriteLine(isTrue.ToString());
booList = new List<bool> { false, false, false, false };
isTrue = booList.Any(b => b);
Console.WriteLine(isTrue.ToString());
あなたはただ使うかもしれませんif(test1 && test2 || ...)
または、複数のステップに分割することもできます
すべての個別の変数がありますか、それとも配列/リストにありますか?後者の場合、それらをループで反復することができます。
bool result = true;
foreach (bool b in boolArray)
{
result = result op b;
}
LINQ の方法 (値が配列にあると仮定):
bool result = (from index in Enumerable.Range(0, tests.Length - 1)
where tests[index] && tests[index + 1]
select index).Any();
ブール比較を単純に排除できます
if( (test1 && test2))
と同等ですif(test1 == true && test2 == true)
私が考えることができる最短はこれです:
if((test2 && (test1 || test3)) || (test3 && test4)) {
//Do Stuff
}
気にしない場合は、ブール値をリストに入れてlinqで使用してください
例えば
bool test1 = true;
bool test2 = true;
bool test3 = true;
bool test4 = true;
List<bool> booList = new List<bool>{test1, test2, test3, test4};
bool isTrue = booList.All(b => b == true); //This will return true
bool test5 = false;
booList.Add(test5);
bool isFalse = booList.All(b => b == true); //This will return false
PS: if ステートメントと比較してパフォーマンスがどうなるかわかりません
char test[x]
... test[x] init ...
i=0
res=0
while( i < x-2 )
{
res |= test[i] && test[i+1]
}
C# を使用すると、ブール値をロジックで処理できます。:)
bool1 の場合、アイスクリームを購入します。
bool1 が存在しない場合は、アイスクリームを購入しないでください。
値を 0 と比較するときは、not 演算子 (!) を使用できます。
if(!bool1)MessageBox.Show("アイスクリームメイトはいません");
0 と比較する場合も同様です。not 演算子 (!) を適用しないでください。
if(bool1)MessageBox.Show("アイスクリーム:D");
混乱させてしまったらごめんなさい。
したがって、他の投稿に追加するには、次のようにします。
if(bool1 && bool2 || bool1 && bool3)MessageBox.Show("アイスクリーム!");