简体   繁体   中英

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:

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. Then I get 1 2 and I will get not exists because 1 2 or 2 1 is not stored.

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> . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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