基本上我有一个实现IEquatable的容器(下面显示的样本)
public class ContainerClass : IEquatable<ContainerClass>
{
public IEnumerable<CustomClass> CustomClass { get; set; }
public override bool Equals(object obj) { ... }
public bool Equals(ContainerClass other) { ... }
public static bool operator ==(ContainerClass cc1, ContainerClass cc2) { ... }
public static bool operator !=(ContainerClass cc1, ContainerClass cc2) { ... }
public override int GetHashCode() { ... }
}
和一个也实现IEquatable
的CustomClasspublic class CustomClass : IEquatable<CustomClass>
{
public string stringone { get; set; }
public string stringtwo { get; set; }
public override bool Equals(object obj) { ... }
public bool Equals(CustomClass other) { ... }
public static bool operator ==(CustomClass cc1, CustomClass cc2) { ... }
public static bool operator !=(CustomClass cc1, CustomClass cc2) { ... }
public override int GetHashCode() { ... }
}
这一切都运行正常,例如,以下工作
IEnumerable<CustomClass> customclassone = new List<CustomClass>
{
new CustomClass { stringone = "hi" },
new CustomClass { stringone = "lo" }
};
IEnumerable<CustomClass> customclasstwo = new List<CustomClass>
{
new CustomClass { stringone = "hi" }
};
var diff = customclassone.Except(customclasstwo);
ContainerClass containerclassone = new ContainerClass
{
CustomClass = customclassone.AsEnumerable()
};
ContainerClass containerclasstwo = new ContainerClass
{
CustomClass = customclasstwo.AsEnumerable()
};
var diff2 = containerclassone.CustomClass.Except(customclasstwo.CustomClass);
在此代码之后,枚举时diff和diff2都包含预期结果。但是,如果我再尝试
IEnumerable<CustomClass> oldCustom = oldContainerClass.CustomClass;
IEnumerable<CustomClass> newcustom = newContainerClass.CustomClass;
var exceptlist = oldCustom.Except(newcustom);
当我尝试枚举exceptlist时,我得到“至少有一个对象必须实现IComparable。”。 oldCustom和newCustom与上述工作示例中的唯一区别在于它们的填充方式。任何人都知道为什么会这样?
答案 0 :(得分:13)
我怀疑您试图对ContainerClass.CustomClass
的这些内容进行排序。由于延迟执行,在您遍历它并且Except()
只是一个红色鲱鱼之前,您不知道有问题。 CustomClass
未实现IComparable
接口,因此排序失败并显示该错误。您的CustomClass
应该实施IComparable<T>
界面,或者您应该在IComparer
上传递OrderBy()
。
如,
oldContainerClass.CustomClass = someListOfSomeType.OrderBy(x => x.CustomClasss, myComparer)
.Select(x => x.CustomClass);
虽然有助于了解您为这些属性分配了什么,但我们可以为您提供更准确的理由。