自定义比较HashSet元素的方法

4
我正在尝试为我的类创建自定义比较器:
```html

我正在尝试为我的类创建自定义比较器:

```
using System.Collections.Generic;

namespace i.changed.namespaces.DataStructures
{
public class Edge
{
    public Cords startPoint, endPont;
    public double length;

    //more code here that doesnt matter
}

public class EdgeComparer : IEqualityComparer<Edge>
{
    public bool Equals(Edge x, Edge y)
    {
        //Check whether the objects are the same object. 
        if (x.Equals(y)) return true;

        return x.startPoint.Equals(y.startPoint) && x.endPont.Equals(y.endPont) && (x.length - y.length < 0.0001);

    }

    public int GetHashCode(Edge obj)
    {
        int hash = 17;
        hash = hash * 23 + obj.length.GetHashCode();
        hash = hash * 23 + obj.startPoint.GetHashCode();
        hash = hash *23 + obj.endPont.GetHashCode();

        return hash;
    }
}

我正在另一个对象中使用这个类:

using i.changed.namespaces.DataStructures;
namespace i.changed.namespaces
public class MyClass
{
   HashSet<Edge> Edges, NewEdges;
   public MyClass()
   {
      NewEdges = new HashSet<Edge>();
      Edges = new HashSet<Edge>();
   }

在某个时候,我希望获得这些哈希集合的并集:

newEdges.UnionWith(Edges);

但是看起来它从未以这种方式使用我的EdgeComparer。我做错了什么?

2
你是否使用了 public HashSet(IEqualityComparer<T> comparer) 构造函数来构建 HashSet<T>? - Johnny
@Lepijohnny稍微修改了问题,以展示结构。 - CrazyWu
1
修改构造函数调用以传递 EdgeComparer。它应该使用您的自定义比较器,例如:new HashSet<Edge>(new EdgeComparer())。 - Johnny
1
正如 @Lepijohnny 所提到的,当您创建 HashSet 时,请传递 EqualityComparer。 - Rudresha Parameshappa
1
@Lepijohnny,是的,你说得对。我自己没有找到这种构建方式。它帮了我很大的忙,谢谢。请随意将其发布为答案。 - CrazyWu
1个回答

6

HashSet<T>提供了一个构造函数,您可以在其中传递自定义的IEqualityComparer<T>实现。如果您传递它,那么它将被使用,否则HashSet<T>将使用默认的IEqualityComparer<T>进行构造。

解决您的问题的方法是稍微修改您的代码,并将您的EdgeComparer传递到HasSet<Edge>构造函数中

public MyClass()
{
    NewEdges = new HashSet<Edge>(new EdgeComparer());
    Edges = new HashSet<Edge>(new EdgeComparer());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接