使用LINQ比较/匹配整数数组的更快方法?

时间:2022-05-18 22:50:02

I have the following code which compares 6 integers in 2 arrays. Is it possible to do this quicker with LINQ? Perhaps with Enumerable.Intersect()? I need it to compare all 6 integers in both arrays.

我有以下代码比较2个数组中的6个整数。使用LINQ可以更快地完成这项工作吗?也许使用Enumerable.Intersect()?我需要它来比较两个数组中的所有6个整数。

        int i = 0;
        int counter = 0;            
        bool jackpot = false;
        int[] randomArr = new int[6];                          
        int[] chosenArr = { 1, 2, 3, 4, 5, 6 };
        Random rNum = new Random();

        while (!jackpot)
        {
            i = 0;
            while (i != chosenArr.Length)
            {
                randomArr[i] = rNum.Next(1, 46);
                i += 1;
            }
            i = 0;
            while (i != chosenArr.Length)
            {
                if (!randomArr.Contains(chosenArr[i])) { break; }
                i += 1;
            }
            if (i == chosenArr.Length) { jackpot = true; }
            counter += 1;
        }

EDIT: I need it to match the integers in both arrays even if they are out of sequence.

编辑:我需要它来匹配两个数组中的整数,即使它们不在序列中。

1 个解决方案

#1


1  

If they have to be in the same order tou could use SequenceEqual

如果它们必须处于相同的顺序,那么tou可以使用SequenceEqual

bool areEqual = chosenArr.SequenceEqual(randomArr);

If they can be in any order then you could use All

如果它们可以按任何顺序排列,那么您可以使用All

bool areEqual = chosenArr.All(randomArr.Contains);

#1


1  

If they have to be in the same order tou could use SequenceEqual

如果它们必须处于相同的顺序,那么tou可以使用SequenceEqual

bool areEqual = chosenArr.SequenceEqual(randomArr);

If they can be in any order then you could use All

如果它们可以按任何顺序排列,那么您可以使用All

bool areEqual = chosenArr.All(randomArr.Contains);