而不是GroupBy
考虑实施IEquatable
和使用Enumerable.Distinct
.
public class ThreeDPoint : IEquatable{ 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; } }
现在做:
var points = new List{ // Add elements }; points.Distinct();
编辑:
如果你仍然相信你想要GroupBy
(我肯定会推荐使用这种IEquatable
方法),你可以这样做:
var list = new List{ 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());