我有一个Objs的HashSet与Obj定义如下:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这工作正常但我在HashSet.Add(obj)返回false 时从HashSet中检索时遇到问题.什么是检索的最佳方式_id的Obj一个已经包含在HashSet在这种情况下?
我看到它的方式:sum + description(用于hashcode,equals)= key和_id(你想要检索的内容)= value.
该场景清楚地指向字典而不是散列集....集合不适用于任意查找/检索.