Penguen
Penguen

Reputation: 17288

How can I compare two generic collections?

How can I compare two generic collections? Here's my attempt with two string arrays, but it doesn't 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);
        }
    }
}

Upvotes: 3

Views: 1709

Answers (3)

TimothyP
TimothyP

Reputation: 21755

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;
}

Upvotes: 2

schoetbi
schoetbi

Reputation: 12856

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

 var newInXY = xx.Except(xy);

Upvotes: 1

Tim Robinson
Tim Robinson

Reputation: 54734

Call Enumerable.SequenceEqual:

bool arraysAreEqual = xx.SequenceEqual(yy);

Upvotes: 8

Related Questions