Search code examples
c#linqequalityentityset

Best way to check two EntitySets equality basied on one of their proprties?


I have two Objects from the same Class, lets say it named as Class1, Class1 has an EntitySet of ClassChild,
What is the best way to indicate that these Two objects have the same exact ClassChild's EntitySets (values and count) based on one property of the ClassChild (string one)?

Thank you.


Solution

  • You can use the SequenceEqual-method:

    bool equal = obj1.ClassChildren.SequenceEqual(obj2.ClassChildren)
    

    That uses the default equality comparer to use a custom one see HERE or this example:

    class ClassChildComparer : IEqualityComparer<ClassChild>
    {
        public bool Equals(ClassChild x, ClassChild y)
        {
            return x.Property == y.Property;
        }
    
        // If Equals() returns true for a pair of objects then GetHashCode() must return the same value for these objects.
        public int GetHashCode(ClassChild c)
        {
            return c.Property.GetHashCode();
        }
    
    }
    
    //and then:
    
    bool equal = obj1.ClassChildren.SequenceEqual(obj2.ClassChildren, new ClassChildComparer())