gpt4 book ai didi

c# - 使用 GroupBy 消除 List 中的重复对象

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:09 33 4
gpt4 key购买 nike

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

最佳答案

而不是 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; }
}

现在做:

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());

关于c# - 使用 GroupBy 消除 List<T> 中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384950/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com