[英]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 2
或2 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.