Home > database >  Compare array c#
Compare array c#

Time:10-08

Create a method named ArrayCompare that compares between two arrays and returns a boolean indicating whether they contain exactly the same elements or not. Its input should be two integer arrays a and b. Its output should be a boolean, where it will return true if a and b contain the same elements and false otherwise

Hello, I am new to c#, and I would like to know how this is done. I read up some documents and I can only come up with this.

    static bool ArrayCompare(int [] i , int [] j)
    {
        if (i.Length == j.Length)
        {
            for (int o = 0; o < i.Length; o  )
            {

                //I am stuck here
                return false;
            }
        }
        return false;
    }

CodePudding user response:

 static bool ArrayCompare(int [] i , int [] j)
    {
        if (i.Length == j.Length)
        {
            for (int o = 0; o < i.Length; o  )
            {
                if(i[o]!=j[o])
                   return false;
            }
            return true;
        }
        return false;
    }

CodePudding user response:

You can check using the code blow

int[] array1 = { 1, 2, 2 };
int[] array2 = { 1, 2, 2 };

bool check = array1.SequenceEqual(array2);

CodePudding user response:

    static bool ArrayCompare(int[]a, int [] b)
    {

        if(a.Length == b.Length)
        {
            for(int i = 0; i < a.Length; i  )
            {
                if (a[i] == b[i])
                {
                    if(a[a.Length - 1] == b[b.Length - 1])
                    {
                        return true;
                    }
                }
                break;
                   
            }
        }

        return false;

    }

This method takes in two int arrays as parameters, we are then checking to first make sure that both the arrays are the same length before we loop. In the for loop we are checking to make sure that if the current index of the first array is the same as the current index of the second array is the same. If it is, we get the to last index of both arrays, and if the same we return true, if the indexes are not the same we return false. We can then create two arrays and console out the method with the two arrays as paramaters.

  • Related