简体   繁体   English

Array.Exists 与 Array.Contains:为什么会出现意想不到的结果?

[英]Array.Exists verses Array.Contains: Why unexpected results?

In Visual Studio using C#, I have created a random number in Main so there is only one seed for the method ShuffleMyNumbersArray which attempts to fill the array with unique numbers from 1 to 52. When I use Array.Contains the results are repeatedly correct.在使用 C# 的 Visual Studio 中,我在 Main 中创建了一个随机数,因此ShuffleMyNumbersArray方法只有一个种子,该方法尝试用从 1 到 52 的唯一数字填充数组。当我使用Array.Contains时,结果反复正确。 However when I use Array.Exists there are number duplications in the array with no apparent pattern.但是,当我使用Array.Exists时,数组中存在数字重复,没有明显的模式。 My question is why is this happening?我的问题是为什么会这样? What is it about Array.Exists that I do not understand?我不明白的Array.Exists是什么? The only thing I can think of is that it may have something to do with the "Not" comparison != num .See the following code for comparison.唯一能想到的是可能跟“Not”比较有关系!= num 。看下面代码对比。

Code that works consistently:始终如一的代码:

public static void ShuffleMyNumbersArray(int[] array, Random rand)
{
    int num = rand.Next(1, 53);
    int i = 0;
    do
    {
        if (array.Contains(num))
        {
            num = rand.Next(1, 53);
        }
        else
        {
            array[i] = num;
            i++;
            num = rand.Next(1, 53);
        }
    } while (i < 52);
}

Code that produces duplicate numbers in the array:在数组中产生重复数字的代码:

public static void ShuffleMyNumbersArray(int[] array, Random rand)
{
    int num = rand.Next(1, 53);
    int i = 0;
    do
    {
        if (Array.Exists(array, element => element != num))
        {
            array[i] = num;
            i++;
            num = rand.Next(1, 53);
        }
        else
        {
            num = rand.Next(1, 53);
        }
    } while (i < 52);
}

Array.Exists(array, element => element != num) means if there is at least one element in the array that is not equal to num . Array.Exists(array, element => element != num)表示array中至少有一个元素不等于num the correct condition is .Array,Exists(array, element => element == num) which means there is no element in the array that equals to num正确的条件是.Array,Exists(array, element => element == num)这意味着array中没有元素等于num

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM