简体   繁体   English

正确使用 IEqualityComparer 的 GetHashCode

[英]Using GetHashCode of IEqualityComparer the right way

When using IEqualityComparer to compare objects in a collection, I'm not sure which one of the followings approaches is the best one.当使用IEqualityComparer比较集合中的对象时,我不确定以下哪一种方法是最好的。

Here is the implementation :这是实现:

class CarComparer : IEqualityComparer<Car>
{
    public bool Equals(Car x, Car y)
    {
        throw new NotImplementedException();
    }

    public int GetHashCode(Car car)
    {
        //
    }
}

And here are my two options for GetHashCode implementation这是我实现GetHashCode两个选项

    public int GetHashCode(Car row)
    {
        return HashCode.Combine(row.Name, row.Color , row.Size);
    }

Or,要么,

    public int GetHashCode(Car row)
    {
        return row.GetHashCode();
    }

I don't like the first one because it make code less maintainable and probably less expensive in terms of resources.我不喜欢第一个,因为它使代码的可维护性降低,并且在资源方面可能更便宜。 But a lot of people use it like that.但是很多人都是这样使用的。

I would like to use my CarComparer in linq functions later.我想CarComparer在 linq 函数中使用我的CarComparer Like this:像这样:

cars.Distinct(new CarComparer());

Which one should I use?我应该使用哪一种?

Is this an opinion based question?这是一个基于意见的问题吗?

The correct answer:正确答案:

When using LINQ the GetHashCode is called before the Equals method and only when the result of the GetHashCode is equal for two items in the collection.使用 LINQ 时, GetHashCodeEquals方法之前调用并且仅当GetHashCode的结果对于集合中的两个项目相等时。

So GetHashCode must be override too :所以GetHashCode必须被覆盖:

  public int GetHashCode(Car row)
{
    return HashCode.Combine(row.Name, row.Color , row.Size);
}

See full response here 在此处查看完整回复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM