我有一个Venue类和一个Coordinate类,如下所示:

class Venue
{
    string Name;
    Coordinate coordinate;
}

class Coordinate
{
    double latitute;
    double longitude;
}


现在,我希望能够根据如下所示的坐标来选择场地:

List<Venue> venues = GetAllVenues();

var myVenue = venues.FirstOrDefault(venue=>venue.coordinate == myCoordinate);


我有一个IEqualityComparer实现,但是lambda表达式没有将IEqualityComparer作为参数的重载。

如何在lambda表达式中使用我的相等比较器?

编辑:

我的平等比较器如下所示:

class CoordinatesEqualityComparer:IEqualityComparer<Coordinate>
    {
        public bool Equals(Coordinate x, Coordinate y)
        {
            return x.RowIndex == y.RowIndex && x.ColumnIndex == y.ColumnIndex;
        }

        public int GetHashCode(Coordinate obj)
        {
            return obj.GetHashCode();
        }
    }


当我像这样执行Union()操作时,即使两个列表中的坐标相同,它也无法正常工作。

List<Coordinates> coordinates;
CoordinatesEqualityComparer comparer;
coordinates.Union(someOtherListOfCoordinates, comparer);


但是,当我与自己进行联合时,它会起作用。我究竟做错了什么?它与GetHashCode()实现有关吗?

编辑2:
修复GetHashCode()方法似乎可以解决问题。

public int GetHashCode(Coordinates obj)
        {
            // Warning:Hack. Use two prime numbers to generate a hash based on two properties.
            return obj.RowIndex.GetHashCode() * 7 + obj.ColumnIndex.GetHashCode() * 13 ;
        }

最佳答案

你有没有尝试过:

var ec = new YourEqualityComparer();
var myVenue = venues.FirstOrDefault(venue =>
                                         ec.Equals(venue.coordinate, myCoordinate));






当然,另一种方法是为==类定义Coordinate运算符,然后就不需要IEqualityComparer了:

class Coordinate
{
    double latitude;
    double longitude;

    public override bool Equals(object obj)
    {
        return Object.ReferenceEquals(this, obj)) ||
               this == (other as Coordinate);
    }

    public static bool operator ==(Coordinate l, Coordinate r)
    {
        return ((object)l == null && (object)r == null) ||
               ((object)l != null && (object)r != null) &&
               // equality check including epsilons, edge cases, etc.
    }

    public static bool operator !=(Coordinate l, Coordinate r)
    {
        return !(l == r);
    }
}

关于c# - 在Lambda表达式中使用相等比较器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28004696/

10-12 23:21