当我运行此语法时,我的消息框告诉我该值存在于数组2中,并且我收到一条消息,指出该值不存在。
导致两条消息显示的原因是什么?我如何重写以解决这个问题?
string[] Arr1 = new string[] { "Game1", "Game2", "Game3" };
string[] Arr2 = new string[] { "Vid1", "Vid2", "Vid3" };
string[] Arr3 = new string[] { "Con1", "Con2", "Con3" };
string sVal = "Vid1";
if (Arr1.Any(x => x == sVal))
{
MessageBox.Show("Value Exists in Array 1");
}
if (Arr2.Any(x => x == sVal))
{
MessageBox.Show("Value Exists in Array 2");
}
if (Arr3.Any(x => x == sVal))
{
MessageBox.Show("Value Exists in Array 3");
}
else
{
MessageBox.Show("Value Does Not Exists in Any Array");
}
string[] Arr1 = new string[] { "Game1", "Game2", "Game3" };
string[] Arr2 = new string[] { "Vid1", "Vid2", "Vid3" };
string[] Arr3 = new string[] { "Con1", "Con2", "Con3" };
string sVal = "Vid1";
bool in1 = Arr1.Contains(sVal);
bool in2 = Arr2.Contains(sVal);
bool in3 = Arr3.Contains(sVal);
if (!in1 && !in2 && !in3)
MessageBox.Show("Value Does Not Exists in Any Array");
else
{
if (in1)
MessageBox.Show("Value Exists in Array 1");
if (in2)
MessageBox.Show("Value Exists in Array 2");
if (in3)
MessageBox.Show("Value Exists in Array 3");
}
// Output: Value Exists in Array 2
代码的最后一部分:
if (Arr3.Any(x => x == sVal))
{
MessageBox.Show("Value Exists in Array 3");
}
else
{
MessageBox.Show("Value Does Not Exists in Any Array");
}
被认为是单一的if statement
,其中:
Arr3
中找到该值,则消息为"Value Exists in Array 3"
Arr3
中找不到该值,则显示消息"Value Does Not Exists in Any Array"
由于Arr3
不包含"Vid1"
,因此您将始终收到该消息,因为另外两个检查不依赖于最后一个。
你没有正确加入。除了第一个之外,你需要为其他所有东西写“else if”。否则只有最后一个if连接到else,而另外两个ifs独立,将打印消息。
如果某个值可以在多个数组中,则应添加一个bool变量,并在其中一个if为true时将其设置为true。