繁体   English   中英

如何存储一对我可以检查是否已经存储的ID?

[英]How to store a pair of ids that I can check if I stored it already?

我有以下问题:

我有一对ID,例如:

1 3
3 1
1 2
...

然后,我想将其存储在某种结构中,这样我就可以简单地检查是否已经有此连接: 1 3已存储,所以当我得到3 1我将看到1 3存在并且它将返回存在。 然后我得到1 2 ,我将不存在,因为没有存储1 22 1

如何实现这一目标,或者什么是一个好的结构?

听起来您想要这样的东西:

// You could turn this into a struct if you wanted.
public sealed class IdPair : IEquatable<IdPair>
{
    private readonly int first;
    private readonly int second;

    public int First { get { return first; } }
    public int Second { get { return second; } }

    public IdPair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }

    public override int GetHashCode()
    {
        // This is order-neutral.
        // Could use multiplication, addition etc instead - the point is
        // that {x, y}.GetHashCode() must equal {y, x}.GetHashCode()
        return first ^ second; 
    }

    public override bool Equals(object x)
    {
        return Equals(x as IdPair);
    }

    public bool Equals(IdPair other)
    {
        if (other == null)
        {
            return false;
        }
        return (first == other.first && second == other.second) ||
               (first == other.second && second == other.first);
    }
}

然后,您只需要HashSet<IdPair> 感觉这比使用Dictionary更为自然,因为您实际上没有单个键-您只有一对,两个属性都具有相同的键样,并且您基本上对顺序无关性感兴趣成对平等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM