C# 从包含具有数组元素的类的列表中删除重复项
我有一个包含类中对象的列表。包含各种项的类,包括int和double数组。这个班看起来像这样C# 从包含具有数组元素的类的列表中删除重复项,c#,list,duplicate-removal,C#,List,Duplicate Removal,我有一个包含类中对象的列表。包含各种项的类,包括int和double数组。这个班看起来像这样 public class NewChildren { public double[] fitnessValue{get;set;} public int[] locationScheme{get;set;} public double crowdingDistance{get;set;} } 由于列表中可能包含重复的项目,我有兴趣删除它们。在web上,我看到了一些基于Lin
public class NewChildren
{
public double[] fitnessValue{get;set;}
public int[] locationScheme{get;set;}
public double crowdingDistance{get;set;}
}
由于列表中可能包含重复的项目,我有兴趣删除它们。在web上,我看到了一些基于Linq的解决方案,它们使用Distinct()和GroupBy()方法。但是,这些方法似乎无法工作,因为对象中存在数组(MSVS2008不会给出任何错误,但也不会删除任何项)
任何建议(包括参考或代码)都将受到高度赞赏。提前感谢。如中所述,Distinct
默认使用默认的相等比较器。默认的相等比较器会将列表中的每个项识别为与所有其他项不同,因为它会检查实例标识
如上述文档所述,为了比较自定义类型并定义所需的相等性,您需要在类上实现一些与比较相关的方法:
public class NewChildren
{
public double[] fitnessValue{get;set;}
public int[] locationScheme{get;set;}
public double crowdingDistance{get;set;}
public bool override Equals(object other)
{
// ... implement your rules for equality here
}
}
要比较自定义数据类型,需要实现[],并为该类型提供自己的方法
默认情况下,通过检查引用相等来计算从类创建的对象的相等方法和相等运算符。这意味着两个项只有在引用同一个类实例时才相等。您需要更改查询以检查类内的各个属性,或者实现对适当方法和运算符的重写 请参阅MSDN上的以下内容:
- 你必须问自己的问题是,当两个
新生子女的实例相同时?由于您有列表,这可能不是一个容易回答的问题。定义后,必须在类中实现equality方法:
public class NewChildren
{
public double[] fitnessValue{get;set;}
public int[] locationScheme{get;set;}
public double crowdingDistance{get;set;}
public bool override Equals(object other)
{
// ... implement your rules for equality here
}
}
现在,要做到这一点,你必须始终遵循。覆盖平等并不是那么简单,尽管它并不复杂。例如,所有数组都具有相同的元素:
public bool override Equals(object other)
{
if (other == null || !(other is NewChildren))
{
return false;
}
var another = (NewChildren)other;
return AreEquivalent(this.fitnessValue, another.fitnessValue)
&& AreEquivalent(this.locationScheme, another.locationScheme)
&& AreEquivalent(this.crowdingDistance, another.crowdingDistance);
}
public static bool AreEquivalent<T>(T[] a, T[] b)
{
return a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a));
}
公共布尔覆盖等于(对象其他)
{
if(other==null | |!(other是NewChildren))
{
返回false;
}
var-other=(NewChildren)other;
返回等效值(此.fitnessValue,另一个.fitnessValue)
&&A等效(此.locationScheme,另一个.locationScheme)
&&a等效(此为拥挤距离,另一为拥挤距离);
}
公共静态布尔等价(T[]a,T[]b)
{
返回a1.OrderBy(a=>a).SequenceEqual(a2.OrderBy(a=>a));
}
数组相等的实现取自。您可以使用进行优化。谢谢。您编写Equals方法的简单示例让我找到了正确的方向,解决了我的问题。@Ehsan,没问题!我是来帮忙的。只是别忘了遵循微软的指导方针,覆盖GetHashCode
。您可能还需要重写运算符==
(只需委托给Equals即可)。感谢您的澄清和参考。