从包含带有数组元素的类的列表中删除重复项 [英] Remove Duplicate Items from a List Containing a Class with Array Elements

查看:78
本文介绍了从包含带有数组元素的类的列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含类对象的列表.该类包含各种项目,包括int和double数组.该类看起来像这样.

I've got a list containing objects from a class. The class which contains various items including int and double arrays. The class looks something like this.

public class NewChildren
{
    public double[] fitnessValue{get;set;}

    public int[] locationScheme{get;set;}

    public double crowdingDistance{get;set;}
}

由于列表中可能包含重复的项目,因此我有兴趣删除它们.在网络上,我看到了一些基于Linq的解决方案,这些解决方案使用Distinct()和GroupBy()方法.但是,这些方法似乎无法使用,因为对象中存在数组(MSVS2008不会给出任何错误,但是也不会删除任何项).

As the list might contain duplicate items, I'm interested in removing them. On the web, I've seen some solutions based on Linq which use Distinct() and GroupBy() methods. However, it seems that these methods won't work as there is arrays in objects (the MSVS2008 won't give any error, but no item is removed either).

任何建议(包括参考或代码)均受到高度赞赏.预先感谢.

Any suggestion (including references or codes) is highly appreciated. Thanks in advance.

推荐答案

您必须问自己的问题是,当NewChildren的两个实例相同时?由于您在那里有列表,因此这可能不是一个容易回答的问题.定义此方法后,必须在类中实现均等方法:

The question you must ask yourself is, when two instances of NewChildren are the same? Since you have lists there, this may not be an easy question to answer. When you have defined this, you must implement the equality method in your class:

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
    }
}

现在,要这样做,您必须始终遵循

Now, to do so, you must always follow Microsoft guidelines. Overriding equality is not that simple, although it's not complex. As an example, where you'd have all arrays with the same elements:

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));
}

数组相等性的实现来自此处.您可以使用此参考对其进行优化.

The implementation of array equality was taken from here. You can optimize it using this reference.

这篇关于从包含带有数组元素的类的列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆