Comparing two arrays in C#

2020-03-01 02:08发布

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

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.

标签: c# arrays
11条回答
劳资没心,怎么记你
2楼-- · 2020-03-01 02:13

If learning is what you seek and an algo is what you're trying to come up with, then using LINQ and any other jazz won't help you.

You need to have 2 nested foreach (or for, whichever you prefer) loops, and once you found a member in the first loop matching a member in the second loop, set your boolean variable to true and break the loops

查看更多
闹够了就滚
3楼-- · 2020-03-01 02:15

Eventhough LINQ will help you to do this with one line of code, It is better to understand how it works because you mentioned the word Algorithm in your question :)

Loop thru the array and compare each item with the items in the second array. If it is present, return true. else false. I would wrap that in a function like this

public bool IsPresentInArray(int[] firstArray, int[] secondArray)
{
    foreach (var itemA in firstArray)
    {
        foreach (var itemB in secondArray)
        {
            if (itemB == itemA)
            {                       
                return true;
            }
        }
    }
    return false;
}

Now i can call it like this

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

bool present= IsPresentInArray(a, b);

Read about foreach loop here

查看更多
啃猪蹄的小仙女
4楼-- · 2020-03-01 02:20

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

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

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 };

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
    }
}

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


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;
        }
    }
}

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.

查看更多
成全新的幸福
5楼-- · 2020-03-01 02:20
hasDuplicates = a.Intersect(b).Any();

You can use LINQ Intersect method - http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx

查看更多
乱世女痞
6楼-- · 2020-03-01 02:22

Not the most performant, but probably easiest to understand approach would be something like this:

foreach (int _a in a) { // iterate through all elements in array a (as _a)
    foreach (int _b in b) { // iterate through all elements in array b (as _b)
        if (_a == _b) { // if we've got a duplicate
            hasDuplicates = true; // store that for later on
            break; // immediately leave this loop (no point in further looking up)
        }
    }
    if (hasDuplicates) { // if we've got a duplicate
        break; // leave this loop as well (no point in further looking up)
    }
}

Obviously, this is not the most performant solution as the complexity would be O(n²), which means twice the number of elements in any one array will double the amount of time it takes to complete the operation (worst case); twice the number of elements in both arrays will quadruple the amount of time.

More elegant solutions would be the use of predefined methos as described in some of the other solutions, but due to this being homework stuff, I don't expect you're allowed to use these "shortcuts" (or should do so).

Always remember: Even if you find solutions here, try to understand them, use them for inspiration, and then write your own. That's probably the best way to learn. Don't just copy & paste.

查看更多
来,给爷笑一个
7楼-- · 2020-03-01 02:27

I used an "IndexOf" and "foreach" loop to create this. (Note: the first 3 "string" lines are just an example of how you could create an array and get it into the proper format).

If you want to compare 2 arrays, they will be semi-colon delimited, but the last value won't have one after it. If you append a semi-colon to the string form of the array (i.e. a;b;c becomes a;b;c;), you can match using "x;" no matter what position it is in:

bool found = false;
string someString = "a-b-c";
string[] arrString = someString.Split('-');
string myStringArray = arrString.ToString() + ";";

foreach (string s in otherArray)
{
    if (myStringArray.IndexOf(s + ";") != -1) {
       found = true;
       break;
    }
}

if (found == true) { 
    // ....
} 
查看更多
登录 后发表回答