views:

89

answers:

1

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);
  }
 }
+3  A: 

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?

Jon Skeet
Building a `Dictionary<TKey, Dictionary<TKey, TValue>>` where the outer dictionary uses a hash to access the fitting inner dictionary. The inner dictionary uses a "normal" equality comparision.
mafutrct
SO question this originated from: http://stackoverflow.com/questions/1784408
mafutrct
I fail to see the use of the expensive hash. Why not just always use the cheap hash, and then equality for collisions? But if you really, really want to go this route, then you'll just need to implement your own IEqualityComparer. As you say, it'll be easy (even trivial) to do.
Jon Skeet
The cheap hash has a terrible distribution and the expensive hash is... well.. expensive.
mafutrct
Just how terrible is that cheap hash distribution though? And how expensive is the expensive hash vs an equality check? Anyway, you know how to do it if you really, really need to... but don't be surprised that this isn't in the framework :)
Jon Skeet
It's as terrible as hashing folders by their number of contained files is. Very terrible :) --- I'm not really surprised. As you said, such a class should not exist normally.
mafutrct