views:

40

answers:

1

i try to compare two class comp1,comp2 i used method below: ComparerCollection(array_X, array_Y); but there are errors below. Arraylist generated from Ilist. how can i do that?

namespace GenericCollecitonComparer
{
    class Program
    {
        static void Main(string[] args)
        {
            myClass comp1 = new myClass() { ID = 1, Name = "yusuf" };
            myClass comp2 = new myClass() { ID = 1, Name = "yusufk" };
            Comparer com = new Comparer(comp1, comp2);
            Console.ReadKey();
        }
    }

    public class Comparer
    {
        public Comparer(myClass x, myClass y)
        {
            PropertyInfo[] propInfo_X = x.GetType().GetProperties();
            PropertyInfo[] propInfo_Y = y.GetType().GetProperties();
            ArrayList array_X = new ArrayList();
            ArrayList array_Y = new ArrayList();

            foreach (PropertyInfo pi in propInfo_X)
                array_X.Add(pi.GetValue(x, null));
            foreach (PropertyInfo pi in propInfo_Y)
                array_Y.Add(pi.GetValue(y, null));

           // ComparerCollection(array_X, array_Y); --> Error below


        }
        public bool ComparerCollection<T>(IList<T> xlist, IList<T> ylist)
        {
            return xlist.SequenceEqual(ylist);
        }
    }

    public class myClass
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

}

 /*  Error  1   The type arguments for method '
             * GenericCollecitonComparer.Comparer.ComparerCollection<T>(System.Collections.Generic.IList<T>, System.Collections.Generic.IList<T>)'
             * cannot be inferred from the usage. Try specifying the type arguments explicitly.
             * 
           */

+1  A: 

The error you receive is due to the fact ArrayList is not a generic class. You can use List<object> instead to make it work.

An alternative implementation:

public class Comparer
{
    public bool AreEqual { get; private set; }

    public Comparer(myClass x, myClass y)
    {
        var xProperties = x.GetType().GetProperties();
        var yProperties = y.GetType().GetProperties();

        var xPropertiesValues = xProperties.Select(pi => pi.GetValue(x, null));
        var yPropertiesValues = yProperties.Select(pi => pi.GetValue(y, null));

        AreEqual = xPropertiesValues.SequenceEqual(yPropertiesValues);
    }
}

And a usage example:

[Test]
public void UsageExample()
{
    myClass comp1 = new myClass() { ID = 1, Name = "yusuf" };
    myClass comp2 = new myClass() { ID = 1, Name = "yusufk" };
    myClass comp3 = new myClass() { ID = 1, Name = "yusuf" };

    Comparer comparerOf1And2 = new Comparer(comp1, comp2);
    Assert.IsFalse(comparerOf1And2.AreEqual);

    Comparer comparerOf1And3 = new Comparer(comp1, comp3);
    Assert.IsTrue(comparerOf1And3.AreEqual);
}
Elisha