I recently needed a dictionary for a small project. Nothing special there but on this occasion, I needed a dictionary that was keyed by two sub-keys. I thought about using an array but you loose strong typing. I thought about using a dictionary of dictionaries but the code is messy, complicated and difficult to maintain. Here is a better solution. (I also coded structures that allow for compound keys with 3 and 4 values. If you need that, just expand on the 2 key version.):
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct CompoundKey<T1, T2>
{
private T1 key1;
private T2 key2;
public CompoundKey(T1 key1, T2 key2)
{
this.key1 = key1;
this.key2 = key2;
}
public T1 Key1
{
get { return this.key1; }
}
public T2 Key2
{
get { return this.key2; }
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append('[');
if (this.Key1 != null)
{
builder.Append(this.Key1.ToString());
}
builder.Append(", ");
if (this.Key2 != null)
{
builder.Append(this.Key2.ToString());
}
builder.Append(']');
return builder.ToString();
}
}
My dictionary:
Dictionary<CompoundKey<int, string>, string> dictionary = new Dictionary<CompoundKey<int, string>, string>();
dictionary.Add(new CompoundKey<int, string>(1, "A"), "X123");
dictionary.Add(new CompoundKey<int, string>(2, "B"), "M394");
dictionary.Add(new CompoundKey<int, string>(3, "B"), "M395");
if (dictionary.ContainsKey(new CompoundKey<int, string>(3, "B")))
{
Fred = dictionary[new CompoundKey<int, string>(3, "B")];
}