Home  /  Questions  /  Question



85   96.4
Dec 16, 2010


How do I create a multiple-key dictionary?

Hi:

I have a need for a multiple-key dictionary. For example: 

Dictionary<Key1, Key2, Key3, Value>

where Key1, Key2, and Key3 have different type.

Thanks.



1,128   99.9
Dec 20, 2010
You can also use Tuple, to achieve this...

HTH!


namespace MultiKeyDictionary.Console {
    using System.Collections.Generic;
    using System;

    internal class Program {
        private static void Main(string[] args) {
            var dictionary = new Dictionary<Tuple<string,string>, string>();

            var key = new Tuple<string, string>("multiple", "keys");
            var value = "Open Sesame!";

            dictionary.Add(key, value);
            Console.WriteLine(dictionary[key]);
        }
    }

    public struct Tuple <T1, T2> {
        public readonly T1 Item1;
        public readonly T2 Item2;

        public Tuple(T1 item1, T2 item2) {
            Item1 = item1;
            Item2 = item2;
        }
    }
}

 

121   96.7
Dec 16, 2010
Zhang:

What if you create a unique hash for the 3 concatenated keys?
Then use this as the unique key in a regular Dictionary.

So, something like:

Dictionary<string, object> dictionary = new Dictionary<string, object>();

and then:

dictionary.Add( Hash(key1, key2, key3), myObject);

where Hash is a simple method that concatenates the 3 keys (the arguments) and returns a hash.