问题描述
我正在尝试将两个Definition
类型的哈希集与EqualityComparer<T>.Default.Equals(value, oldValue)
进行比较. Definition
定义如下
I am trying to compare two hashsets of Definition
type as EqualityComparer<T>.Default.Equals(value, oldValue)
. Definition
is defined as follows
public class Definition
{
public string Variable { get; set; }
public HashSet<Location> LocationList { get; set; }
public override bool Equals(object obj)
{
Definition other = obj as Definition;
return other.Variable.Equals(this.Variable) && other.LocationList!= null &&this.LocationList != null
&& other.LocationList.Count == this.LocationList.Count
&& other.LocationList == this.LocationList;
}
public override int GetHashCode()
{
return this.Variable.GetHashCode() ^ this.LocationList.Count.GetHashCode();// ^ this.LocationList.GetHashCode();
}
}
public class Location
{
public int Line { get; set; }
public int Column { get; set; }
public int Position { get; set; }
public string CodeTab { get; set; }
public Location(int line, int col, int pos, string tab)
{
Line = line;
Column = col;
Position = pos;
CodeTab = tab;
}
public override bool Equals(object obj)
{
Location other = obj as Location;
return this.CodeTab == other.CodeTab
&& this.Position == other.Position
&& this.Column == other.Column
&& this.Line == other.Line;
}
public override int GetHashCode()
{
return this.CodeTab.GetHashCode() ^ this.Position.GetHashCode()
^ this.Column.GetHashCode() ^ this.Line.GetHashCode();
}
}
对于类似的集合,尽管所有信息保持相同,但结果仍将以false
的形式返回.唯一的区别是某些元素的位置可以互换,但是我知道HashSet
在比较时不会保留或检查顺序.有人可以告诉我这里出了什么问题吗?
Somehow for a similar set, the result is returned as false
despite all the information remaining the same. The only difference is that the position of some elements are interchanged, but I know that HashSet
won't preserve or check the order while comparing. Can any one advise me on what is going wrong here?
PS:我也尝试取消注释this.LocationList.GetHashCode()
,但是没有用.
PS: I tried uncommenting this.LocationList.GetHashCode()
also, but didn't work.
推荐答案
您需要为集合创建一个比较器:
You need to create a comparer for the sets:
var setComparer = HashSet<Location>.CreateSetComparer();
return other.Variable.Equals(this.Variable) && setComparer.Equals(this.LocationList, other.LocationList);
这篇关于使用对象的HashSet检查相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!