实现此目的的一种方法是创建IEqualityComparer<T> 并使用interface 将两个类链接在一起。
X 和 Y 字段需要转换为属性来实现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; }
}
然后你可以创建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;
}
}
}
要检查它们,您可以使用以下代码。这是一个简单的用法。
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());
如果你真的不想订购它们,你可以使用以下方法:
bool temp = list1.All(x => list2.Contains(x, new ListComparer()))
&& list2.All(x => list1.Contains(x, new ListComparer()));;