Dan*_*986 3 c# tuples list distinct
我有一个看起来像这样的元组列表:
List<Tuple<double, double, double, string, string, string>> myList;
双精度值表示 XYZ 坐标值,字符串是附加到这些坐标的某些属性。
现在我想使用该myList.lis.Distinct().ToList()方法过滤掉任何重复项。毕竟,1 个坐标可以是一条线的起点,而另一个是另一条线的终点,但是当它们连接时,我在列表中两次获得点 XYZ 点,但具有其他字符串属性。但我只想在元组的 3 个双精度值上使用 Distinct 并忽略字符串。
到目前为止,我还没有想出如何做到这一点。这可能吗,怎么可能?
您可以GroupBy像这样使用linq 方法:
var result = myList.GroupBy(x => new {x.Item1, x.Item2, x.Item3})
.Select(x => x.First())
.ToList();
Run Code Online (Sandbox Code Playgroud)
演示在这里
创建新类并重写Equals方法以仅使用坐标:
class Point
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public string Property1 { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as Point);
}
protected bool Equals(Point other)
{
return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode * 397) ^ Y.GetHashCode();
hashCode = (hashCode * 397) ^ Z.GetHashCode();
return hashCode;
}
}
}
Run Code Online (Sandbox Code Playgroud)