Hash table with two primary keys

Using System.Collectionshow to create a collection with two primary keys?

I mean, new entries with the same combination are excluded, but each key can be used with other keys (for example, combining two primary keys in SQL)

+3
source share
3 answers

You can simply use struct, for example:

struct CompositeKey<T1,T2>
{
  public T1 Item1;
  public T2 Item2;
}

Then use this as a key.

+5
source

You can use Tuple if you are using .NET 4.0.

Otherwise, you can create a Tuple yourself.

Found in StackOverFlow: Tuples (or arrays) as dictionary keys in C #

struct Tuple<T, U, W> : IEquatable<Tuple<T,U,W>>
{
    readonly T first;
    readonly U second;
    readonly W third;

    public Tuple(T first, U second, W third)
    {
        this.first = first;
        this.second = second;
        this.third = third;
    }

    public T First { get { return first; } }
    public U Second { get { return second; } }
    public W Third { get { return third; } }

    public override int GetHashCode()
    {
        return first.GetHashCode() ^ second.GetHashCode() ^ third.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }
        return Equals((Tuple<T, U, W>)obj);
    }

    public bool Equals(Tuple<T, U, W> other)
    {
        return other.first.Equals(first) && other.second.Equals(second) && other.third.Equals(third);
    }
}
+2

As with LaGrandMere, you can use System.Tuple if you are using .NET 4.0 or later:

Tuple<int,string> key = Tuple.Create(0, "Test");

Also note that if you put strings, ints, etc. as keys in dictionaries, you have to make a special case that it would be NULL in SQL. Cannot have a null key in the dictionary.

var dict = new Dictionary<Tuple<string, int>, string>();

var address1 = Tuple.Create("5th Avenue",15);
var address2 = Tuple.Create("5th Avenue",25);
var address3 = Tuple.Create("Dag Hammarskjölds väg", 4);

dict[address1] = "Donald";
dict[address2] = "Bob";
dict[address3] = "Kalle";

// ...

int number = Int32.Parse("25");
var addressKey = Tuple.Create("5th Avenue",number);
string name = dict[addressKey]; // Bob
+2
source

Source: https://habr.com/ru/post/1785379/


All Articles