我如何使用GroupBy获得一个明确的点列表.我想消除重复点.
List<_3DPoint> list_of_points = new List<_3DPoint> { ... };
public class _3DPoint
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
而不是GroupBy考虑实施IEquatable<ThreeDPoint>和使用Enumerable.Distinct.
public class ThreeDPoint : IEquatable<ThreeDPoint>
{
public bool Equals(ThreeDPoint other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((ThreeDPoint) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode*397) ^ Y.GetHashCode();
hashCode = (hashCode*397) ^ Z.GetHashCode();
return hashCode;
}
}
public static bool operator ==(ThreeDPoint left, ThreeDPoint right)
{
return Equals(left, right);
}
public static bool operator !=(ThreeDPoint left, ThreeDPoint right)
{
return !Equals(left, right);
}
public ThreeDPoint(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public double X { get; private set; }
public double Y { get; private set; }
public double Z { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
现在做:
var points = new List<ThreeDPoint> { // Add elements };
points.Distinct();
Run Code Online (Sandbox Code Playgroud)
编辑:
如果你仍然相信你想要GroupBy(我肯定会推荐使用这种IEquatable<T>方法),你可以这样做:
var list = new List<ThreeDPoint>
{
new ThreeDPoint(1.0, 2.0, 3.0),
new ThreeDPoint(1.0, 2.0, 3.0),
new ThreeDPoint(2.0, 2.0, 2.0),
new ThreeDPoint(2.0, 2.0, 2.0)
};
var distinctResult = list.GroupBy(x => new { x.X, x.Y, x.Z })
.Select(x => x.First());
Run Code Online (Sandbox Code Playgroud)