简体   繁体   English

具有两个主键的哈希表

[英]Hash table with two primary keys

Using System.Collections how to create a collection with two primary keys ?使用System.Collections如何创建具有两个主键的集合?

I mean new entries with the same combination are avoided but each key can be used with other keys (like combining two primary keys in SQL )我的意思是避免使用具有相同组合的新条目,但每个键都可以与其他键一起使用(例如在SQL组合两个主键)

You can simply use a struct , example: 您可以简单地使用struct ,例如:

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

Then use that as the key. 然后用它作为关键。

Like LaGrandMere said, you can use System.Tuple if you're on .NET 4.0 or later: 就像LaGrandMere所说,如果你使用的是.NET 4.0或更高版本,你可以使用System.Tuple

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

Also, note that if you're putting strings, ints etc as keys in dictionaries you're going to have to special-case what would've been NULL in SQL. 另外,请注意,如果您将字符串,整数等作为字典中的键,那么您将需要特殊情况下SQL中的NULL。 Can't have a null-key in a 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

You can use Tuple if you're using .NET 4.0. 如果您使用的是.NET 4.0,则可以使用Tuple

Else you can create a Tuple by yourself. 否则你可以自己创建一个元组。

Found on StackOverFlow : Tuples( or arrays ) as Dictionary keys in C# 在StackOverFlow上找到: 元组(或数组)作为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);
    }
}

you can also construct composite key and use that in dictionary您还可以构造复合键并在字典中使用它

var compositeKey = key1.ToString()+key2.ToString();

var dict = new Dictionary<string,object>();
dict.Add(compositekey,val);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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