Search code examples
c#.netgethashcode

Generate unique key from hashcode


I am having class below

class Group
{
    public Collection<int> UserIds { get; set; }
    public int CreateByUserId { get; set; }
    public int HashKey { get; set; }
}

I want to generate some unique hashkey based on UsersIds[] and CreateByUserId and store it to mongo and search on it.

Conditions:

  1. each time the hashkey should me same for same UsersIds[] and CreateByUserId
  2. hashkey should be different when number of users increases in UsersIds[]

In a soultion for this I am overriding GetHashCode() function:

public override int GetHashCode()
{
    unchecked
    {
        var hash = (int)2166136261;
        const int fnvPrime = 16777619;

        List<int> users = new List<int>() { CreateByUserId };
        UserIds.ToList().ForEach(x => users.Add(x));
        users.Sort();

        users.ForEach(x => hash = (hash * fnvPrime) ^ x.GetHashCode());
        return hash;
    }
}

Is it a better solution or suggest some better solution.


Solution

  • So if the intention is to save the hash value in the database dont override GetHashCode on the object, that is for use with HashTables (Dictionary, HashSet..) in conjunction with Equals and not unique enough for your purpose. Instead use an established hash function such as SHA1 for example.

    public string Hash(IEnumerable<int> values)
    {
       using (var hasher = new SHA1Managed())
       {
        var hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(string.Join("-", values)));
        return BitConverter.ToString(hash).Replace("-", "");
       }
    }
    

    Usage:

    var hashKey = Hash(UsersIds.Concat(new[]{ CreateByUserId });
    

    Sort UsersIds if so desired.