I'm generating 64 bit hashcodes from strings, and storing this value in a database
Is it possible to override GetHashCode with a 64 bit long type instead of 32 byte int?
If this is not possible, is it possible to implement Equals and GetHashCode somewhere else, and still use Except and Intersect?
public class RecordComparer : IEqualityComparer<Record>
{
public bool Equals(Record x, Record y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return x.RecordHash.Equals(y.RecordHash);
}
public long GetHashCode(Record obj)
{
return obj.RecordHash;
}
}
Assuming that you do not care about the possible problems arising from different records having equal hash codes and thus being considered equal even though they are different you can simply implement
RecordComparer
like this:IEqualityComparer<T>
is correctly implemented by returning a 32 bit hash code created by truncating the 64 bit hash code identifying the record.There is no requirement that
GetHashCode
should return unique hash codes for unequal records. However, avoiding collisions will make generic collections likeDictionary<Record>
perform better and basing the 32 bit hash code on the 64 bit hash code is probably the best thing to do.If you look at the source code for
Enumerable.Except
andEnumerable.Intersect
you can see that they use the internal classSet<T>
which is some sort of hash table so your implementation ofGetHashCode
can affect the performance of your code but not the correctness (as long as equal records return the same hash code).