c# - 仅用循环比较两个数组

标签 c# arrays compare

我被数组困住了,需要一些帮助。
我有两个数组,我正在使用 foreach 循环比较它。我希望程序只在 winningNumbers 中有两个数字时才写“你赢了”匹配 someNumbers .如果只有一场比赛,输出应该是“你输了”
(我必须使用循环来解决这个问题)

int[] someNumbers = { 1, 2, 3, 4, 5, 6 };
int[] winningNumbers = { 1, 2, 13, 14, 15, 16 };
bool winning = false;

foreach (var item1 in someNumbers)
{
    foreach (var item2 in winningNumbers)
    {
        if (item1 == item2)
        {
            winning = true;
        }
    }
}

if (winning == true )
{
    Console.WriteLine("You won");
}

else
{
    Console.WriteLine("You lost");
}

最佳答案

由于您正在遍历每个数组,因此每次遇到匹配项时都可以增加一个计数器。

            int[] someNumbers = { 1, 2, 3, 4, 5, 6 };
            int[] winningNumbers = { 1, 2, 13, 14, 15, 16 };
            int matches = 0;

            foreach (var item1 in someNumbers)
            {
                foreach (var item2 in winningNumbers)
                {
                    if (item1 == item2)
                    {
                        matches++;
                    }
                }
            }

            if (matches == 2 )
            {
                Console.WriteLine("You won");
            }

            else
            {
                Console.WriteLine("You lost");
            }

关于c# - 仅用循环比较两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63002706/

相关文章:

c# - 关于依赖注入(inject),何时使用抽象类与接口(interface)?

c++ - 检查数组中消息的最有效方法

python - 为什么我需要指定此列表的大小,否则它会给出列表索引超出范围错误

java - 从2个for循环中的java中的2个ArrayList中删除元素

c++ - 如何在 C++ 中测试相关对象的相等性?

c# - 如何正确显示启动画面

c# - DateTime.ParseExact 不适用于 "yyyy-MM-dd HH:mm:ss"

c# - ASP.NET MVC : How to use linq lambda expression with a ViewModel to get data?

python - 如何判断一个日期是否在另外两个日期之间?

list - `predsort/3` 的可能行为