I have a HashSet
of a type:
public Class Person
{
int? _requestedHashCode;
long Id;
Name string;
DateTime BirthDate;
// Other properties
public bool IsTransient()
{
return this.Id == default(long);
}
public override int GetHashCode()
{
if (!IsTransient())
{
if (!_requestedHashCode.HasValue)
_requestedHashCode = this.Id.GetHashCode() ^ 31;
return _requestedHashCode.Value;
}
else
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is Person))
return false;
if (Object.ReferenceEquals(this, obj))
return true;
if (this.GetType() != obj.GetType())
return false;
Entity item = (Entity)obj;
if (item.IsTransient() || this.IsTransient())
return false;
else
return item.Id == this.Id;
}
}
I have a method that receives as parameter the ID of the person, and I would like to get the person with O(1) performance:
public Person GetPerson(long paramIdPersonToDelete)
{
return _myHashset.FirstOrDefault(x => x.Id == paramIdPersonToDelete);
}
Is my implementation correct? I am not sure what I need to modify; the comparison that needs the HashSet
, if the HashSet
uses GetHashCode()
, or Equals()
or both.
Thanks.