简体   繁体   English

比较两个复杂对象的相等性

[英]Comparing equality of two complex objects

I have two List, this complex object has 4 public properties of reference type.我有两个 List,这个复杂的对象有 4 个引用类型的公共属性。 How can i compare one list to another to find if those lists are equal in size and by values.我如何将一个列表与另一个列表进行比较,以确定这些列表的大小和值是否相等。

I have implemented Equals in ComplexObject in order to help with equality checks我在 ComplexObject 中实现了 Equals 以帮助进行相等检查

public Type1 Type1 { get; set; }
public IEnumerable<Type2> Type2s{ get; set; }
public Type3 Type3{ get; set; }
public Type4 Type4 { get; set; }

public bool Equals(ComplexObject complexObject)
{
    int type2sCount = Type2s.Count();
    return Type1 .Equals(complexObject.Type1) &&
        Type3.Equals(complexObject.Type3) &&
        Type4.Equals(complexObject.Type4) &&
        Type2s.Intersect(complexObject.Type2s).Count() == type2sCount;
}

I need also to print out items that do no fit or have no pair in second list我还需要打印出第二个列表中不适合或没有配对的项目

Thanks谢谢

If you sort both lists first, you can use the SequencyEqual extension method to check that both sequences are equal.如果先对两个列表进行排序,则可以使用SequencyEqual扩展方法来检查两个序列是否相等。 This method is part of System.Linq.此方法是 System.Linq 的一部分。

Here's an example:下面是一个例子:

    List<ComplexObject> list1 = new List<ComplexObject>();
    List<ComplexObject> list2 = new List<ComplexObject>();

    IOrderedEnumerable<ComplexObject> list1Sorted = list1.OrderBy(item => item.SomeProperty);
    IOrderedEnumerable<ComplexObject> list2Sorted = list2.OrderBy(item => item.SomeProperty);

    bool areEqual = list1Sorted.SequenceEqual(list2Sorted);

The simplest approach for the lists would be SequenceEqual , but you need to be careful about null s:列表的最简单方法是SequenceEqual ,但您需要小心null s:

public bool Equals(ComplexObject complexObject)
{
    bool eq = Equals(Type1, complexObject.Type1)
        && Equals(Type3, complexObject.Type3)
        && Equals(Type4, complexObject.Type4);
    if (eq)
    {
        if(Type2s == null)
        {
            if(complexObject.Type2s != null) eq = false;
        } else {
            eq = complexObject.Type2s == null ? false
               : Type2s.SequenceEqual(complexObject.Type2s);
        }
    }
    return eq;
}

Check out the IEqualityComparer(T).查看 IEqualityComparer(T)。 You implement the interface members and if you are using LINQ, it will work, you should be able to AND the lists.您实现了接口成员,如果您使用的是 LINQ,它将起作用,您应该能够对列表进行 AND 操作。 http://msdn.microsoft.com/en-us/library/ms132151.aspx http://msdn.microsoft.com/en-us/library/ms132151.aspx

您可以使用SequenceEqual(List1, List2)

  bool equal = Type2s.SequenceEqual(complexObject.Type2s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM