Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of searching HashSet

Tags:

c#

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?

like image 369
ashishduh Avatar asked Jul 22 '13 20:07

ashishduh


1 Answers

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.

like image 178
Vivek Avatar answered Oct 29 '22 20:10

Vivek