首先,我会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();