[英]C# && , || Operators
I have some values from MySQL . 我有一些来自MySQL的价值。 and I want to know ... how I can do the following : 我想知道...我该怎么做:
if (Value.ToString() == "1" || Value.ToString() == "2" || Value.ToString() == "3" && SecondValue.ToString() == "5")
Value can be : 1 "or" 2 "or" 3 ... and Second Value "5" . 值可以是:1“或” 2“或” 3 ...和第二值“ 5”。 means One of (the three "Value") && SecondValue . 表示(三个“值”)之一和&SecondValue。 or there is no way to do that ? 还是没有办法做到这一点? and I should just do this : 我应该这样做:
if (Value.ToString() == "1" && SecondValue.ToString() == "5"
{
}
if (Value.ToString() == "2" && SecondValue.ToString() == "5"
{
}
ect ....
Thank you for your answer . 谢谢您的回答 。
Your code is almost correct but you need to add an extra parenthesis around the "or" conditions to group them. 您的代码几乎是正确的,但是您需要在“或”条件周围添加一个额外的括号以对它们进行分组。
if ((Value.ToString() == "1" || Value.ToString() == "2" || Value.ToString() == "3")
&& SecondValue.ToString() == "5")
我认为您要尝试的是:
if (new List<string>() { "1", "2", "3" }.Contains(Value.ToString()) && SecondValue.ToString() == "5")
You can use parenthesis to group your boolean conditions however you want. 您可以根据需要使用括号将布尔条件分组。 If you want a case where "one of these cases is true and also one of these other cases is true", group the cases appropriately. 如果需要“其中一种情况为真,而其他情况之一为真”的情况,请对这些情况进行适当的分组。 In your case, you'd be better off using a collection to hold your values for valid cases for "Value", something like: 就您而言,最好使用集合来保存“值”的有效案例的值,例如:
var myValue = Value.ToString();
var myValidCases = new [] {"1", "2", "3"};
if(myValidCases.Any(validCase => validCase == myValue) && SecondValue.ToString() == "5")
{
//do something
}
if
(
(
Value.ToString() == "1" ||
Value.ToString() == "2" ||
Value.ToString() == "3"
) &&
SecondValue.ToString() == "5"
)
Here's what it looks like basically: 基本上是这样的:
(Value == 1 && SecondValue == 5) || (Value == 2 && SecondValue == 5) || (Value == 3 && SecondValue == 5)
Now the && operator is very much like the multiplication operator in that it is distributive . 现在&&运算符非常像乘法运算符,因为它是分布式的 。 Which means we can do this: 这意味着我们可以这样做:
(Value == 1 || Value == 2 || Value == 3) && SecondValue == 5
Try this, it is clean enugh: 试试这个,这很干净:
if (SecondValue.ToString() == "5")
{
if (Value.ToString() == "1" || Value.ToString() == "2" || Value.ToString() == "3")
{
//Do Stuff
}
}
Regards, Krekkon 问候,克雷克孔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.