Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex object comparison in C# [duplicate]

Tags:

c#

I have two complex objects of the same type. I want to compare both the objects to determine if they have the exact same values. What is the efficient way of doing this ?

sample class structure given below:

class Package
{
    public List<GroupList> groupList;
}
class GroupList
{
   public List<Feature> featurelist;
}
class Feature
{
   public int qty;
}
like image 755
jbagavathi Avatar asked Feb 05 '26 19:02

jbagavathi


1 Answers

Okay, so you want deep unordered structural comparison. The "unordered" part is tricky, and in fact it is a strong hint that your classes are not designed right: List<T> is inherently ordered, so perhaps you would rather want to use a HashSet<T> there (if you don't expect to have any duplicates). Doing so would make the comparison both easier to implement, and faster (though insertions would be slower):

class Package
{
    public HashSet<GroupList> groupList;

    public override bool Equals(object o)
    {
        Package p = o as Package;
        if (p == null) return false;
        return groupList.SetEquals(p.groupList);
    }

    public override int GetHashCode()
    {
        return groupList.Aggregate(0, (hash, g) => hash ^ g.GetHashCode());
    }
}

class GroupList
{
   public HashSet<Feature> featureList;

    public override bool Equals(object o)
    {
        GroupList g = o as GroupList;
        if (g == null) return false;
        return featureList.SetEquals(g.featureList);
    }

    public override int GetHashCode()
    {
        return featureList.Aggregate(0, (hash, f) => hash ^ f.GetHashCode());
    }
}

class Feature
{
    public int qty;

    public override bool Equals(object o)
    {
        Feature f = o as Feature;
        if (f == null) return false;
        return qty == f.qty;
    }

    public override int GetHashCode()
    {
        return qty.GetHashCode();
    }
}

If you want to keep using List<T>, you'll need to use LINQ set operations - note, however, that those are significantly slower:

class Package
{
    public List<GroupList> groupList;

    public override bool Equals(object o)
    {
        Package p = o as Package;
        if (p == null) return false;
        return !groupList.Except(p.groupList).Any();
    }
}

class GroupList
{
   public List<Feature> featureList;

    public override bool Equals(object o)
    {
        GroupList g = o as GroupList;
        if (g == null) return false;
        return !featureList.Except(f.featureList).Any();
    }
}
like image 54
Pavel Minaev Avatar answered Feb 07 '26 10:02

Pavel Minaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!