Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

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 »