0

如何为我的用户定义对象使用 distinct 方法以便没有两个点是相同的?


//这是我的课

class PointD
{
    private double m_dPointDx;
    private double m_dPointDy;
}

这是我的包含 PointD 对象的列表

List<PointD> listPoints = new List<PointD>();
listPoints.Add(new PointD(10,45));
listPoints.Add(new PointD(20,65));
listPoints.Add(new PointD(10,45));

现在如何区分列表以便没有两个点是相同的?

4

1 回答 1

1

首先,我会PointD像这样重新定义类:

class PointD
{
    public double M_dPointDx;
    public double M_dPointDy;
    public PointD(double x, double y)
    {
        M_dPointDx = x;
        M_dPointDy = y;
    }
}

定义以下实现IEqualityComparer<PointD>接口的类:

class MyComparer : IEqualityComparer<PointD>
{
    public bool Equals(PointD x, PointD y)
    {
        //Check whether the compared objects reference the same data. 
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null. 
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the PointD' properties are equal. 
        return x.M_dPointDx==y.M_dPointDx && x.M_dPointDy==y.M_dPointDy;
    }

    // If Equals() returns true for a pair of objects  
    // then GetHashCode() must return the same value for these objects. 

    public int GetHashCode(PointD pointD)
    {
        //Check whether the object is null 
        if (Object.ReferenceEquals(pointD, null)) return 0;

        //Get hash code for the M_dPointDx field if it is not null. 
        int hashX = pointD.M_dPointDx == null ? 0 : pointD.M_dPointDy.GetHashCode();

        //Get hash code for the M_dPointDy field. 
        int hashY = pointD.M_dPointDy.GetHashCode();

        //Calculate the hash code for the PointD. 
        return hashX ^ hashY;
    }
}

然后,你有这个用法:

List<PointD> listPoints = new List<PointD>();
listPoints.Add(new PointD(10, 45));
listPoints.Add(new PointD(20, 65));
listPoints.Add(new PointD(10, 45));

var distinctItems = listPoints
    .Distinct(new MyComparer())
    .ToList();
于 2013-06-11T13:00:20.520 回答