[英]How to store a pair of ids that I can check if I stored it already?
I have the following problem: 我有以下问题:
I have pairs of Ids like: 我有一对ID,例如:
1 3
3 1
1 2
...
Then I want to store it in some structure, so that I can simply check if I have this connection already: 1 3
is stored, so when I get 3 1
I will see that 1 3
exists and it will return exist. 然后,我想将其存储在某种结构中,这样我就可以简单地检查是否已经有此连接:
1 3
已存储,所以当我得到3 1
我将看到1 3
存在并且它将返回存在。 Then I get 1 2
and I will get not exists because 1 2
or 2 1
is not stored. 然后我得到
1 2
,我将不存在,因为没有存储1 2
或2 1
。
How to implement this, or what would be a good structure for this? 如何实现这一目标,或者什么是一个好的结构?
It sounds like you want something like: 听起来您想要这样的东西:
// 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);
}
}
Then you just need a HashSet<IdPair>
. 然后,您只需要
HashSet<IdPair>
。 It feels like this is a more natural approach than using a Dictionary
, as you don't really have a single key - you just have a pair where both properties are equally key-like, and you're basically interested in an order-neutral equality of pairs. 感觉这比使用
Dictionary
更为自然,因为您实际上没有单个键-您只有一对,两个属性都具有相同的键样,并且您基本上对顺序无关性感兴趣成对平等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.