C#中的复杂对象比较

jba*_*thi 3 c#

我有两个相同类型的复杂对象.我想比较两个对象,以确定它们是否具有完全相同的值.这样做的有效方法是什么?

样本类结构如下:

class Package
{
    public List<GroupList> groupList;
}
class GroupList
{
   public List<Feature> featurelist;
}
class Feature
{
   public int qty;
}
Run Code Online (Sandbox Code Playgroud)

Pav*_*aev 5

好的,所以你想要深度无序的结构比较."无序"部分很棘手,事实上它强烈暗示你的类没有正确设计:List<T>本身是有序的,所以也许你宁愿在HashSet<T>那里使用(如果你不希望有任何重复) .这样做会使比较更容易实现,并且更快(尽管插入会更慢):

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想继续使用List<T>,你需要使用LINQ设置操作 - 但请注意,这些操作要慢得多:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)