【问题标题】:What is the better approach to compare a collection with another (architecturely speaking)?将集合与另一个集合(从架构上讲)进行比较的更好方法是什么?
【发布时间】:2011-01-17 02:54:10
【问题描述】:

这是我目前最喜欢的架构方法的一个示例:

public abstract class CollectionComparer {
    public virtual SetEqual(IEnumerable enum1, IEnumerable enum2) {
        if(enum1== null && enum2== null)
            return true;

        if(enum1== null && !(enum2== null))
            return false;

        if(!(enum1== null) && enum2== null)
            return false;

        if(enum1.GetType().DeclaringType != enum2.GetType().DeclaringType)
            return false;

        var col1 = (from e in enum1 select e).ToList()
        var col2 = (from e in enum2 select e).ToList()

        if(col1.Count != col2.Count)
            return false;           

        foreach (element in col1)
            if(!col2.Contains(element))
                return false;

        foreach (element in col2)
            if(!col1.Contains(element))
                return false;

        return true; 
    }
}

public interface IProduct {
    ...
}

public interface IOrder {
    ...
    ICustomer Customer { get; }
    ICollection<IProduct> Products { get; }
}

public interface ICustomer {
    ...
    ICollection<IOrder> Orders { get; }
}

public internal Order : CollectionComparer, IOrder {
    #region IOrder interface implementation
    ...
    #endregion
}

public internal Customer : CollectionComparer, ICustomer {
    #region ICustomer interface implementation
    ...
    #endregion
}

对于应用于集合的 object.Equals() 的等价物进行集合比较,这种 CollectionComparer 抽象类方法是否被视为一种良好做法?

【问题讨论】:

  • 感谢 Daniel A. White 和“不退货不退款”提供这些非常出色的答案!不幸的是,我只能设置一个答案作为答案。考虑到我确定 collection 是否具有相等比较器的第一个目标,Daniel A. White 的答案是最好的。抱歉不退货不退款!

标签: .net oop ienumerable equals icollection


【解决方案1】:

如何实现 IComparable 并为每个项目和每个项目属性递归调用它?已经有一个定义明确的接口来比较对象。有什么原因你不想/不能使用它吗?

【讨论】:

  • 诚实吗?无知! =P 我从未使用过 IComparable 接口。我想我会留意它。 =)
  • IComparable 在内部被字符串和数字类型用于排序。
  • 感谢 Daniel A. White 提供此信息。我喜欢了解有关它如何在幕后工作的此类信息。
  • 如果你实现IComparable,你的集合中的对象也可以很容易地排序。
  • 这提供了一个很大的优势!谢谢丹尼尔!
【解决方案2】:

【讨论】:

  • @Ram:如果只是为了了解这个 SequenceEqual() 方法,那么也许我的问题很有用? ;P 我在开玩笑!
  • @Will:好的,Will,你的问题也是 +1 !!
  • @Ram:感谢您的支持!这是值得赞赏的,真的!希望有一天我能帮助你解决你未来的一个问题!祝你今天过得愉快! =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 2011-08-10
  • 1970-01-01
  • 2018-06-22
相关资源
最近更新 更多