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

C# 如何存储一对可以检查是否已存储的ID?,c#,C#,我有以下问题: 我有两对ID,如: 1 3 3 1 1 2 ... 然后我想将其存储在某种结构中,这样我就可以简单地检查我是否已经建立了此连接: 13已存储,因此当我获取31时,我将看到13已存在,它将返回exist。 然后我得到12,我将得到不存在,因为12或21未存储 如何实现这一点,或者什么样的结构才是好的呢?听起来您想要的是: // You could turn this into a struct if you wanted. public sealed class IdPair :

我有以下问题:

我有两对ID,如:

1 3
3 1
1 2
...
然后我想将其存储在某种结构中,这样我就可以简单地检查我是否已经建立了此连接:
13
已存储,因此当我获取
31
时,我将看到
13
已存在,它将返回exist。 然后我得到
12
,我将得到不存在,因为
12
21
未存储


如何实现这一点,或者什么样的结构才是好的呢?

听起来您想要的是:

// 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);
    }
}
//如果需要,可以将其转换为结构。
公共密封类IdPair:合格
{
私有只读int-first;
私有只读int秒;
public int First{get{return First;}}
public int Second{get{return Second;}}
公共IdPair(整数第一,整数第二)
{
this.first=first;
这个秒=秒;
}
公共覆盖int GetHashCode()
{
//这是秩序中立的。
//可以用乘法、加法等来代替-重点是
//{x,y}.GetHashCode()必须等于{y,x}.GetHashCode()
返回第一个^second;
}
公共覆盖布尔等于(对象x)
{
返回等于(x为空气);
}
公共布尔等于(IdPair其他)
{
如果(其他==null)
{
返回false;
}
返回(first==other.first&&second==other.second)||
(first==other.second&&second==other.first);
}
}

然后您只需要一个
哈希集
。感觉这是一种比使用
字典
更自然的方法,因为你实际上没有一个键-你只有一对,其中两个属性都是相同的键,您基本上对成对的顺序无关的相等性感兴趣。

字典键/值?您可以对ID进行排序并存储排序。使用字典引用:正如前面所说,您应该使用
字典
,并且您应该考虑创建适配器类,该类将接受您的成对并对它们进行排序(例如,比较AWA在同一行上的想法,但考虑使用struct或仅使用一个类。这比使用像
public class IdPair
这样的简单类型更好吗?请解释一下好吗?@unlimit:这是一个像
public class IdPair
这样的简单类型-为了清晰起见,它只实现了
IEquatable
,并且是EALE是为了避免平等过度多态性的丑恶。是否有一个用户
IdPair
而不是
Tuple
?@Brian:是的,平等是不同的。你可以使用
Tuple
和一个自定义的
IEqualityComparer
,但它的代码数量差不多,而且它的含义也不太清楚:这里我们是非常好的具体说明这两个值是什么……它们不仅仅是任意两个整数。@JonSkeet:谢谢,我没有注意到这两个整数是无序的。