简体   繁体   中英

Is there a built-in IEqualityComparer that compares objects only using their hash value?

Is there a built-in IEqualityComparer that compares objects by the value returned by their GetHashCode value? It's easy to write, but I'd prefer to use a provided class instead of a custom one.

Current code:

private class HashComparer : IEqualityComparer<TKey>
{
    private readonly Func<TKey, int> _Hasher;

    public HashComparer (Func<TKey, int> hasher)
    {
        _Hasher = hasher;
    }

    public bool Equals (TKey x, TKey y)
    {
        // null supposed to throw, therefore no check
        return _Hasher (x) == _Hasher (y);
    }

    public int GetHashCode (TKey obj)
    {
        return _Hasher (obj);
    }
}

No, such a thing doesn't exist in the framework as far as I'm aware.

It would be a generally Bad Thing - hash codes don't have to be unique, so it couldn't be used to mimic normal equality, other than for types with 2^32 possible values or fewer, and a hash generation algorithm which gives a unique code for each value.

I'm struggling to think of any sensible use for this - which is why you're unlikely to find it in the framework. Perhaps there's some very specialized situation where you'd find it useful, but that's not enough justification to put it in the main framework.

Out of interest, what are you trying to do with it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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