对比在C#两个数组 [英] Comparing two arrays in C#

查看:94
本文介绍了对比在C#两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool hasDuplicate = false;   
int[] a = new int[] {1, 2, 3, 4};
int[] b = new int[] { 5, 6, 1, 2, 7, 8 };

我需要数组A的所有元素比较数组b元素和B中重复的元素的情况下,设置为TRUE hasDuplicate。

I need compare all elements of array A with element of array B and in case of a duplicate element in B, set hasDuplicate on TRUE.

推荐答案

由于这是家庭作业,我会给你一个答案的功课。

Since this is Homework, I will give you a homework answer.

当然,你可以使用LINQ和依靠 SequenceEqual 相交等,但很可能不是点运动。

Sure, you could use LINQ and rely on SequenceEqual, Intersect, etc, but that is likely not the point of the exercise.

给定两个数组,你可以遍历数组中的使用的foreach

Given two arrays, you can iterate over the elements in an array using foreach.

int[] someArray;
foreach(int number in someArray)
{
     //number is the current item in the loop
}

所以,如果你有两个数组是相当小的,你可以遍历在所有项目的第一个数组,然后循环的每个数字在第二阵列中进行比较。让我们来试试。首先,我们需要纠正你的数组语法。它应该是这个样子:

So, if you have two arrays that are fairly small, you could loop over each number of the first array, then loop over the all the items in the second array and compare. Let's try that. First, we need to correct your array syntax. It should look something like this:

    int[] a = new int[] {1, 2, 3, 4};
    int[] b = new int[] { 5, 6, 1, 2, 7, 8 };

请注意使用大括号 {。你正在使用的语法来创建一个N维数组。

Note the use of the curly braces {. You were using the syntax to create a N-dimensional array.

bool hasDuplicate = false;
int[] a = new int[] { 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
    foreach (var numberB in b)
    {
        //Something goes here
    }
}

这会让我们pretty接近。我会鼓励你去尝试它自己从这里开始。如果你还需要帮助,请继续阅读。

This gets us pretty close. I'd encourage you to try it on your own from here. If you still need help, keep reading.

好了,我们基本上只是需要检查,如果数字是相同的。如果是这样,将 hasDuplicate 为true。

OK, so we basically need to just check if the numbers are the same. If they are, set hasDuplicate to true.

bool hasDuplicate = false;
int[] a = new int[] { 8, 1, 2, 3, 4 };
int[] b = new int[] { 5, 6, 7, 8 };
foreach (var numberA in a)
{
    foreach (var numberB in b)
    {
        if (numberA == numberB)
        {
            hasDuplicate = true;
        }
    }
}

这是一个很野蛮的力量的方法。该循环的复杂度为O(n 2 ),但可能不是你的情况关系。使用LINQ其他答案当然是更有效率,如果效率是很重要的,你可以考虑这些。另一种选择是停止的循环利用如果 hasDuplicate 是真实的,还是把这个code在的方法和使用收益来退出方法。

This is a very "brute" force approach. The complexity of the loop is O(n2), but that may not matter in your case. The other answers using LINQ are certainly more efficient, and if efficiency is important, you could consider those. Another option is to "stop" the loops using break if hasDuplicate is true, or place this code in a method and use return to exit the method.

这篇关于对比在C#两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆