HashSet<List<float>> 上的 C# SetEquals 当预期为 true 时为 false

标签 c# .net generics set hashset

一位 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/

相关文章:

c# - 无法启动 wcf 服务主机

c++ - 制作通用链表将下一个指针放在结构的开头

java - 在没有特征对象的 Scala 中重用 Java 泛型集合

c# - 非泛型类中泛型类型的属性

c# - Response.Close() 和 Response.Dispose() 有什么区别?

.net - centos 上最新的单声道

c# - 如何在构造函数中使用 AutoMapper 映射到 "this"

c# - 在 Travis CI 上使用 Mono 5.14.0.177、msbuild 15.0、nuget 4.7.1 构建失败,但在 VirtualBox 中无法重现

c# - Excel 服务无法打开工作簿

c# - AuthCookie 已设置,仍被重定向到 login.aspx