我知道有很多答案建議覆寫等于和哈希碼,但在我的情況下,這是不可能的,因為使用的物件是從 DLL 匯入的。
首先,我有一個名為DeploymentData.
這些物件以及其他屬性包含以下兩個:Location(double x, double y, double z)和Duct(int id)。
目標是洗掉具有相同Location引數的那些。
首先,我將它們按 分組Duct,因為如果它在另一個管道上,則 aLocation不能相同。
var groupingByDuct = deploymentDataList.GroupBy(x => x.Duct.Id).ToList();
然后是實際的演算法:
List<DeploymentData> uniqueDeploymentData = new List<DeploymentData>();
foreach (var group in groupingByDuct) {
uniqueDeploymentData
.AddRange(group
.Select(x => x)
.GroupBy(d => new { d.Location.X, d.Location.Y, d.Location.Z })
.Select(x => x.First()).ToList());
}
這確實有效,但為了正確檢查它們確實是重復的,應該比較整個位置。為此,我做了以下方法:
private bool CompareXYZ(XYZ point1, XYZ point2, double tolerance = 10)
{
if (System.Math.Abs(point1.X - point2.X) < tolerance &&
System.Math.Abs(point1.Y - point2.Y) < tolerance &&
System.Math.Abs(point1.Z - point2.Z) < tolerance) {
return true;
}
return false;
}
但我不知道如何將其應用于上面撰寫的代碼。總結:
- 如果沒有所有這些方法呼叫,我如何撰寫上面的演算法?
- 如何調整上述演算法以使用該
CompareXYZ方法獲得更好的精度? - 效率?
uj5u.com熱心網友回復:
過濾重復項的一種簡單方法是使用帶有自定義相等比較器的 Hashset。這是一個實作 IEqualityComparer 的類,例如:
public class DeploymentDataEqualityComparer : IEqualityComparer<DeploymentData>
{
private readonly double _tolerance;
public DeploymentDataEqualityComparer(double tolerance)
{
_tolerance = tolerance;
}
public bool Equals(DeploymentData a, DeploymentData b)
{
if (a.Duct.id != b.Duct.id)
return false; // Different Duct, therefore not equal
if (System.Math.Abs(a.Location.X - b.Location.X) < _tolerance &&
System.Math.Abs(a.Location.Y - b.Location.Y) < _tolerance &&
System.Math.Abs(a.Location.Z - b.Location.Z) < _tolerance) {
return true;
}
return false;
}
public GetHashCode(DeploymentData dd)
{
// If the classes of the library do not implement GetHashCode, you can create a custom implementation
return dd.Duct.GetHashCode() | dd.Location.GetHashCode();
}
}
為了過濾重復項,您可以將它們添加到 HashSet:
var hashSet = new HashSet<DeploymentData>(new DeploymentDataEqualityComparer(10));
foreach (var deploymentData in deploymentDataList)
hashSet.Add(deploymentData);
這樣,您無需按管道進行分組并使用 HashSet 的增強性能。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431542.html
