HashSet类型的Dictionary.ContainsKey-按元素比较

问题描述 投票:-1回答:2

我想将HashSet的(将包含2个向量)添加到字典中作为键。稍后,我想(快速)检查字典中是否包含由2个向量即时创建的HashSet。我希望包含/相等检查取决于集合中的向量。

Fex。如果我将HashSet [V000 V001]添加到词典中。我想让Dict.ContainsKey(HashSet [V001 V000])返回true。 (HashSet,因此顺序可以变化,只是相同的Elements)

问题似乎是,Dict.ContainsKey确实将单独创建的HashSet视为不同的对象,即使它们包含相同的元素。

Dictionary<HashSet<Vector3>, Vector3> d = new Dictionary<HashSet<Vector3>, Vector3>();

HashSet<Vector3> s = new HashSet<Vector3>();
s.Add(Vector3.one);
s.Add(Vector3.zero);

d.Add(s);


HashSet<Vector3> s2 = new HashSet<Vector3>();
s2.Add(Vector3.zero);
s2.Add(Vector3.one);


bool doesContain = d.ContainsKey(s2);

您也是我考虑的一种更好的快速检查方法。我不确定,这是我正在做的最好的解决方案。也许您已经知道了。我正在检查边缘的总数是否已经包含2点之间的连接。

c# dictionary hashset
2个回答
1
投票

HashSet类型没有开箱即用地进行相等比较。它仅具有引用相等性。

要获得所需的内容,您需要一个新的类型用作Dictionary键。新类型将具有HashSet属性,并重载Equals()GetHashCode(),并且此时也可以实现IEquatable

我会让你开始:

public class HashKey<T> : IEquatable<HashKey<T>>
{
    private HashSet<T> _items;
    public HashSet<T> Items
    {
        get {return _items;}
        private set {_items = value;}
    }

    public HashKey()
    {
        _items = new HashSet<T>();
    }
    public HashKey(HashSet<T> initialSet)
    {
        _items = initialSet ?? new HashSet();
    }

    public override int GetHashCode()
    {
        // I'm leaving this for you to do
    }

    public override bool Equals(Object obj)
    {
        if (! (obj is HashKey)) return false;
        return this.GetHashCode().Equals(obj.GetHashCode());
    }

    public bool Equals(HashSet<T> obj)
    {
        if (obj is null) return false;
        return this.GetHashCode().Equals(obj.GetHashCode());
    }
}      

0
投票

您想使用哈希集作为键。

因此,这些键是引用,其中一个键是一个哈希集引用。

[ContainsKey比较参考。

对于您想做的事情,您可以创建一个实现IEqualityComparer的类,以将其传递给字典构造函数。

https://docs.microsoft.com/dotnet/api/system.collections.generic.iequalitycomparer-1

如果要进行全面管理,则应创建一个新类来嵌入字典,并实现自己的公共操作,将字典的操作包装起来:ContainsKey和所需的所有其他方法。

public class MyDictionary : IEnumerable<>
{

  private Dictionary<HashSet<Vector3>, Vector3> d 
    = new Dictionary<HashSet<Vector3>, Vector3>();

  public int Count { get; }

  public this...

  public ContainsKey()
  {
    // implements your own comparison algorithm
  }

  public Add();

  public Remove();

  ...

}

所以您将拥有一个用于您的预期用途的强类型字典。

© www.soinside.com 2019 - 2024. All rights reserved.