Use GroupBy to eliminate repetitive objects from List<T&g

本文关键字:lt List from to GroupBy eliminate repetitive objects Use | 更新日期: 2023-09-27 18:27:27

如何使用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; }
}

Use GroupBy to eliminate repetitive objects from List<T&g

请考虑实现IEquatable<ThreeDPoint>并使用Enumerable.Distinct,而不是GroupBy

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

现在做:

var points = new List<ThreeDPoint> { // Add elements };
points.Distinct();

编辑:

如果你仍然确信你想要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());

List&lt_3DPoint>list_of_points=新列表&lt_3DPoint>{…};

var noDuplicates=list_of_points.Distinct().ToList();

您可能希望重写Equals和GetHashCode,以便不仅删除列表中的重复引用,还删除Equal Data。