如何使用for循环输出bool

0 c# for-loop

我一直在尝试使用for循环来检查数组中是否存在元素.我似乎无法弄清楚如何做到这一点,因为在for循环内声明的所有变量都无法从其范围之外访问.我该如何正确地做到这一点?

var array = new[] { 3, 4, 2, 6, 3 };
var value = 2;

bool isContained;
for(var i = 0; i < array.Length; i++)
    isContained = (value == array[i]);

if(isContained)
    Console.WriteLine("The value is in the array");
else
    Console.WriteLine("The value is not in the array");
Run Code Online (Sandbox Code Playgroud)

Ond*_*cny 8

除了这样的事实,你的代码甚至不会编译,因为isContained可能永远不会被初始化,问题是你会isContainedfor循环中反复覆盖:

bool isContained;
for(var i = 0; i < array.Length; i++)
    isContained = (value == array[i]);
Run Code Online (Sandbox Code Playgroud)

基本上,当且仅当您找到了正确的值时才需要设置它.所以基本的工作版本是:

bool isContained = false;
for(var i = 0; i < array.Length; i++)
{
    if (value == array[i]) isContained = true;
}
Run Code Online (Sandbox Code Playgroud)

显然,一旦遇到匹配,迭代数组的其余部分是没有意义的.因此这稍微好一些:

bool isContained = false;
for(var i = 0; i < array.Length; i++)
{
    if (value == array[i])
    {
        isContained = true;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是理解这个概念的好方法.但是,正如有人在评论中指出的那样,存在一种更为先进的解决方案,即"单线":

bool isContained = array.Any(x => x == value);
Run Code Online (Sandbox Code Playgroud)