C# group by 消除重复项
我正在处理一个大型兴趣点 (POI) 数据集,这些数据集都有纬度/经度值。
我想过滤掉彼此距离很近的 POI。我认为要实现这一点,我可以将纬度/经度四舍五入到小数点后的 X 位,并按结果进行分组(或调用 Distinct()
或其他方式)...
我编写了一些 LINQ 语句,其中似乎没有做我想要的事情,
var l1 = (from p in PointsOfInterest where p.IsVisibleOnMap select p).Distinct(new EqualityComparer()).ToList();
其中 EqualityComparer
是
public class EqualityComparer : IEqualityComparer<PointOfInterest>
{
public bool Equals(PointOfInterest x, PointOfInterest y)
{
return Math.Round(x.Latitude.Value, 4) == Math.Round(y.Latitude.Value, 4) &&
Math.Round(x.Longitude.Value, 4) == Math.Round(y.Latitude.Value, 4);
}
public int GetHashCode(PointOfInterest obj)
{
return obj.GetHashCode();
}
}
但 Equals 方法似乎永远不会被调用?!?
关于最好的方法有什么想法吗?
Im working with a large dataset of point of interest (POI) which all have Lat/Long values.
I want to filter out POIs that are in close proximity to each other. I think that to achieve this I can round the Lat/Long down to X decimal places and group by the results (or call Distinct()
or whatever)...
I have written a little LINQ statement which doesnt seem to do what I want,
var l1 = (from p in PointsOfInterest where p.IsVisibleOnMap select p).Distinct(new EqualityComparer()).ToList();
where EqualityComparer
is
public class EqualityComparer : IEqualityComparer<PointOfInterest>
{
public bool Equals(PointOfInterest x, PointOfInterest y)
{
return Math.Round(x.Latitude.Value, 4) == Math.Round(y.Latitude.Value, 4) &&
Math.Round(x.Longitude.Value, 4) == Math.Round(y.Latitude.Value, 4);
}
public int GetHashCode(PointOfInterest obj)
{
return obj.GetHashCode();
}
}
but the Equals method never seems to get called?!?
Any thoughts on the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Equals()
永远不会被调用,因为GetHashCode()
为任何两个对象返回不同的值,因为您使用的是中定义的
类。GetHashCode()
System.Object您需要以稍微不同的方式实现 GetHashCode()。
尝试类似的东西
Equals()
never gets called becauseGetHashCode()
returns different values for any two objects because you are usingGetHashCode()
defined inSystem.Object
class .You'll need to implement GetHashCode() a little differently.
try something like
这就是问题所在:
您还必须适当地重写
GetHashCode()
,目前可能所有项目都被视为不同,因为哈希码不匹配。来自 MSDN 的
IEqualityComparer.GetHashCode()
:
This is the problem:
You'll have to override
GetHashCode()
appropriately as well, probably currently all items are considered different because the hash code doesn't match.From MSDN for
IEqualityComparer.GetHashCode()
:简单地:
Simply: