一位 Python 开发人员在这里进行一些 C#(.NET 4.6、Visual Studio 2015 Professional)工作。我正在尝试检查是否有两个 HashSet
s 相等。
我有两个HashSet<List<float>>
我正在尝试使用它进行比较
thisList.SetEquals(otherList);
但是,这会返回 false
在我的数据上。使用 MSDN HashSet
's examples 中的示例确实按预期工作。但是,在样本中他们使用 HashSet<int>
而我使用 HashSet<List<float>>
.
因为我找不到打印 HashSet
的方法将内容放入 Visual Studio 中的立即窗口( ToString
返回 "System.Collections.Generic.HashSet1[System.Collections.Generic.List1[System.Single]]"
),我使用 Json.NET JsonConvert.SerializeObject(thisList);
将数据转储到 .json
磁盘上的文件。
两个文件(每个 HashSet
内容为:
[[10.0,15.0],[20.0,25.0]]
和[[10.0,15.0],[20.0,25.0]]
检查HashSet
调试时 Visual Studio 中的代码如下所示:
- thisList Count = 2 System.Collections.Generic.HashSet<System.Collections.Generic.List<float>>
- [0] Count = 2 System.Collections.Generic.List<float>
[0] 10 float
[1] 15 float
+ Raw View
- [1] Count = 2 System.Collections.Generic.List<float>
[0] 20 float
[1] 25 float
+ Raw View
+ Raw View
- otherList Count = 2 System.Collections.Generic.HashSet<System.Collections.Generic.List<float>>
- [0] Count = 2 System.Collections.Generic.List<float>
[0] 20 float
[1] 25 float
+ Raw View
- [1] Count = 2 System.Collections.Generic.List<float>
[0] 10 float
[1] 15 float
+ Raw View
+ Raw View
每个HashSet
包含两个列表(顺序无关,因为它是一个集合),并且每个列表具有相同的值(具有相同的顺序)。他们应该被视为平等。
我应该做什么来制作这些HashSet
s 被视为等于 thisList.SetEquals(otherList);
?
编辑:
打印coord.ToString("G17")
在每个 float 上:
10
15
20
25
20
25
10
15
最佳答案
因为您在 HashSet 中使用 List,所以它会将两个列表作为引用进行比较,而不是考虑列表中的值。
不要使用 List 来表示 X 和 Y,而是使用 Vector2 或 Point 类。结构或多或少应该是这样的:
public struct Point
{
public double X {get; }
public double Y { get; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public bool Equals(Point other)
{
return X.Equals(other.X) && Y.Equals(other.Y);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Point && Equals((Point) obj);
}
public override int GetHashCode()
{
unchecked
{
return (X.GetHashCode() * 397) ^ Y.GetHashCode();
}
}
}
关于HashSet<List<float>> 上的 C# SetEquals 当预期为 true 时为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50637021/