A HashKey
is a value calculated to check if a call of Equals()
may yield a result that's true
.
The hashkey is used to make a fast desicion if the element may be the right one or if it's for sure the false one.
First thing is, replace the wording HashKey
with Unique Id
.
If you want a unique Id, I'd recommend using the database with a Id column if you store it there anyway and then fetch the Id with the other data. + In mongo DB, each entry also already has a own Id:
See here
Each object in mongo already has an id, and they are sortable in
insertion order. What is wrong with getting collection of user
objects, iterating over it and use this as incremented ID?[...]
That way: Use the DB for the unique ID and calculate your HashKey
(if you need it anymore) with simple cheap math like adding up the user Ids.
To make it programatically:
If you want to check it programatically and we ignore Ids from the DB, you need to implement the GetHashKey()-Function and the Equals()-Function of the given objects.
class Group
{
public Collection<int> UserIds { get; set; }
public int CreateByUserId { get; set; }
public override bool Equals(object obj)
{
Group objectToCompare = (Group)obj;
if (this.UserIds.Count != objectToCompare.UserIds.Count)
return false;
if (this.CreateByUserId != objectToCompare.CreateByUserId)
return false;
foreach (int ownUserId in this.UserIds)
if (!objectToCompare.UserIds.Contains(ownUserId))
return false;
//some elements might be double, i.e. 1: 1,2,2 vs 2: 1,2,3 => not equal. cross check to avoid this error
foreach (int foreignUserId in objectToCompare.UserIds)
if (!this.UserIds.Contains(foreignUserId))
return false;
return true;
}
public override int GetHashCode()
{
int sum = CreateByUserId;
foreach (int userId in UserIds)
sum += userId;
return sum;
}
}
Usage:
Group group1 = new Group() { UserIds = ..., CreateByUserId = ...};
Group group2 = new Group() { UserIds = ..., CreateByUserId = ...};
group1.Equals(group2);
Here is the answer to "Why do we need the GetHashCode-Function when we use Equals?"
Note: This is for sure not the most performant solution for the Equals()
-Method here. Adjust as needed.