Using System.Collections
how to create a collection with two primary keys ?
I mean new entries with the same combination are avoided but each key can be used with other keys (like combining two primary ke开发者_运维百科ys in SQL
)
You can simply use a struct
, example:
struct CompositeKey<T1,T2>
{
public T1 Item1;
public T2 Item2;
}
Then use that as the key.
You can use Tuple if you're using .NET 4.0.
Else you can create a Tuple by yourself.
Found on 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);
}
}
Like LaGrandMere said, you can use System.Tuple if you're on .NET 4.0 or later:
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. 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 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);
精彩评论