Checking equality of arrays with a generic method


In this case we define the equality of two arrays as all array elements are pairwise equal.
The method below compares two arrays and it says that those are equal or not. The first and the second parameter is any kind of array. With the third boolean parameter you can give that method has to ignore position of elements in the array or not. In the method's generic parameter you have to give the type of the arrays. The two arrays must be the same type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SampleApp
{
    public static class Utils
    {
        public static bool arraysAreEquals(Array a1, Array a2, bool ignorePositionOfElements)
        {
            if (a1 == null && a2 == null)
                return true;
            else if ((a1 == null && a2 != null) || (a1 != null && a2 == null))
                return false;
            else
            {
                if (a1.Length != a2.Length)
                    return false;
                else
                {
                    if (ignorePositionOfElements)
                    {
                        Array.Sort(a1);
                        Array.Sort(a2);
                    }
                    for (int i = 0; i < a1.Length; i++)
                    {
                        T x1 = (T)a1.GetValue(i);
                        T x2 = (T)a2.GetValue(i);
                        if (!x1.Equals(x2))
                            return false;
                    }
                }
            }
            return true;
        }
    }
 
    private class Program
    {
        private static void Main(string[] args)
        {
            string[] array1 = new string[] { "cba", "abc", "bca" };
            string[] array2 = new string[] { "bca", "cba", "abc" };
            Utils.arraysAreEquals<string>(array1, array2, false); // result is: false
            Utils.arraysAreEquals<string>(array1, array2, true);  // result is: true
        }
    }
}

Posted on 12:42 by csharper and filed under , , | 1 Comments »

1 comments:

Unknown said... @ 22 October 2010 at 15:03

You've got a lot of
|if (foobar)
| return qux;
|else {
| some more complex code here;
|}

You don't need an 'else' if the 'then' branch returns.
You can save precious indentation this way and significantly increase the readability of your method.

I'm not an expert in C# but it looks strange that you can call Sort on an arbitrary array without defining a comparison function. I have severe doubts that this would work on a user-defined data type (like a class) that does not have compare implemented.

Post a Comment