views:

42

answers:

3

How can i compare 2 string array with generic class? it returns tome true they are equal but not return true....


namespace genericCollections
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] xx = new string[] { "gfdg", "gfgfd", "fgfgfd" };
            string[] yy = new string[] { "gfdg", "gfgfd", "fgfgfd" };
            Console.WriteLine(ComparerCollection(xx, yy).ToString());
            Console.ReadKey();

        }

       static bool ComparerCollection<T>(ICollection<T> x, ICollection<T> y)
        {
           return  x.Equals(y);
        }
    }


}
+5  A: 

Call Enumerable.SequenceEqual:

bool arraysAreEqual = xx.SequenceEqual(yy);
Tim Robinson
A: 

You can get elements that are in xx but not in xy by using LINQ:

 var newInXY = xx.Except(xy);
schoetbi
+2  A: 

Hi,

From the MSDN documenation:

The default implementation of Equals supports reference equality only, but derived classes can override this method to support value equality.

In your case xx and yy are two different instances of string[] so they are never equal. You'd have to override the .Equal() method of the string[]

But you can simply solve it by looping through the entire collection

static bool CompareCollection<T>(ICollection<T> x, ICollection<T> y)
{
       if (x.Length != y.Length)
            return false;

       for(int i = 0; i < x.Length,i++)
       {
           if (x[i] != y[i])
               return false;
       }

       return true;
}
TimothyP