简体   繁体   中英

Comparing arrays in c# based on user input

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

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

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");

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM