【问题标题】:Comparing lists of objects that contain a list of objects比较包含对象列表的对象列表
【发布时间】:2017-01-26 14:26:18
【问题描述】:

我有两个 A 类型的对象列表。

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

B 在哪里

class B
{
    string X;
    string Y;
}

如何在 C# 中检查它们是否相等,忽略元素出现的顺序?

【问题讨论】:

  • 如何比较它们?
  • 检查列表是否相等
  • 如果您想比较它们的值相等性和引用相等性,您可能希望首先在 AB 中覆盖 EqualsGetHashCode
  • @juharr 最好创建一个IEqualityComparer&lt;T&gt; 而不是更改类本身。

标签: c# list compare


【解决方案1】:

实现此目的的一种方法是创建IEqualityComparer&lt;T&gt; 并使用interface 将两个类链接在一起。

XY 字段需要转换为属性来实现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&lt;T&gt;

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()));;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多