0

Trying to compare 2 arrays but not getting it to work

            Console.WriteLine("Entering elements for ths 1st array: ");
        int[] arr1 = new int[3];
        for (int i = 0; i < arr1.Length; i++)
        {
            arr1[i] = Convert.ToInt32(Console.ReadLine());
        }
        Console.WriteLine("Entering the elements for the 2nd array: ");
        int[] arr2 = new int[3];
        for (int i = 0; i < arr2.Length; i++)
        {
            arr2[i] = Convert.ToInt32(Console.ReadLine());
        }
        bool result = Array.Equals(arr1,arr2);
        if (result)
        {
            Console.WriteLine("Equal");
        }
        else
        {
            Console.WriteLine("Not equal");
        }
    }

I keep on getting a Not equal

1

4 Answers 4

3

This doesn't work because Array.Equals() runs Object.Equals method - it compares just references. Use Enumerable.SequenceEqual() instead for example.

Sign up to request clarification or add additional context in comments.

Comments

0

That will never work. These are two different instances of the array. Equals is inherited from Object.

Comments

0

I think you are comparing two obect containers for equality - see this post... What's the fastest way to compare two arrays for equality? you need to compare the contents.

Comments

0

You are not comparing the values stored in the arrays but you are comparing two different instances of an integer array. (the references).
Of course they are different.

If you want to check only if the two arrays contains the same values you could use the SequenceEquals LinQ operator, if you wish to get the difference between the two arrays use Except

if(arr1.SequenceEquals(arr2))
     Console.WriteLine("Equals");
else
     Console.WriteLine("Not equal");

....

int[] diff =  arr1.Except(arr2).ToArray();
if(diff.Length == 0) 
     Console.WriteLine("Equals");
else
     Console.WriteLine("Not equal");

2 Comments

If you're going to use LINQ, just use SequenceEqual. It can short circuit, unlike Except. It also is shorter, and semantically represents what you want to do. Oh, and Except doesn't return an array, it returns an IEnumerable<T>, and so you'd need to use Count, or better yet, Any, instead of Length.
@Servy OMG you are fast. wait

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.