0

I have two lists of objects of type A.

class A
{
    string X;
    string Y;
    List<B> Z;
}

where B is

class B
{
    string X;
    string Y;
}

How do I check if they are equal in C#, ignoring the order in which the elements are present?

Prasann
  • 460
  • 1
  • 5
  • 13

1 Answers1

2

One way to accomplish this would be to create an IEqualityComparer<T> and use an interface to link the two classes together.

The X and Y fields need to be converted to properties to implement the interface.

public interface IInterface
{
    string X { get; set; }
    string Y { get; set; }
}

class A : IInterface
{
    public string X { get; set; }
    public string Y { get; set; }
    List<B> Z;
}

class B : IInterface
{
    public string X { get; set; }
    public string Y { get; set; }
}

Then you can create the IEqualityComparer<T>.

public class ListComparer : IEqualityComparer<IInterface>
{
    public bool Equals(IInterface x, IInterface y)
    {
        return x.X == y.X && x.Y == y.Y;
    }

    public int GetHashCode(IInterface obj)
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 * obj.X.GetHashCode();
            hash = hash * 23 * obj.Y.GetHashCode();
            return hash;
        }
    }
}

To check them you can use the following code. This is a simple usage.

List<A> list1 = new List<A>
{
    new A { X = "X1", Y = "Y1"},
    new A { X = "X2", Y = "Y2"},
    new A { X = "X3", Y = "Y3"}
};
List<B> list2 = new List<B>
{
    new B { X = "X3", Y = "Y3"},
    new B { X = "X1", Y = "Y1"},
    new B { X = "X2", Y = "Y2"}
};

List<A> list1Ordered = list1.OrderBy(x => x.X).ThenBy(x => x.Y).ToList();
List<B> list2Ordered = list2.OrderBy(x => x.X).ThenBy(x => x.Y).ToList();

bool result = list1Ordered.SequenceEqual(list2Ordered, new ListComparer());

If you really didn't want to order them you could use the following:

bool temp = list1.All(x => list2.Contains(x, new ListComparer()))
            && list2.All(x => list1.Contains(x, new ListComparer()));;
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34