I have a HashSet of Objs with Obj defined as such:
public class Obj
{
private int _id;
private string _desc;
private int _sum;
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Description
{
get { return _desc; }
set { _desc = value; }
}
public int Sum
{
get { return _sum; }
set { _sum = value; }
}
public Obj(int id, string desc, int sum)
{
_id = id;
_sum = sum;
_desc = desc;
}
public override bool Equals(Obj other)
{
return this._sum == other._sum
&& this._desc == other._desc;
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + _sum.GetHashCode();
hash = (hash * 7) + _desc.GetHashCode();
return hash;
}
}
This works fine but I'm having trouble retrieving from the HashSet when HashSet.Add(obj)
returns false. What would be the best way to retrieve the _id
of the Obj
that is already contained in the HashSet
in such a case?
The way i see it : sum + description (used for hashcode, equals) = key and _id (what you want to retrieve) = value.
The scenario clearly points to a dictionary rather than a hashset.... sets aren't meant for arbitrary lookup/retrieval.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With