Friday, September 28, 2007
« Connect to and communicate with your Mas... | Main | Zune Software Install Failure. Fix: Enab... »

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")];

}

kick it on DotNetKicks.com   Friday, September 28, 2007 6:43:04 AM (Pacific Standard Time, UTC-08:00)  #    Disclaimer  |  Comments [3]  | 
Friday, December 09, 2011 10:14:02 PM (Pacific Standard Time, UTC-08:00)
I love reading these articles becsaue they're short but informative.
Monday, December 12, 2011 3:41:29 AM (Pacific Standard Time, UTC-08:00)
Saturday, December 17, 2011 5:16:50 PM (Pacific Standard Time, UTC-08:00)
Hi.The article is great.Can you please elaborate on how to access dictionary of dictionary?Example:I want to retrieve the whole inner dictionary based on the outer dictionary key.I want to retrieve inner dictionary key&#8217;s value Thanks in advance.Cheers !

free car insurance quotes
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview