Reputation: 5311
I want to build a dictionary composed by 2 keys and 1 value. Is that possible?
Dictionary<(key1, key2), Type> dict = new Dictionary<(key1, key2), Type>();
Then I want to find in my dictionary by this 2 keys and get the Type. I tried that key1 and key2 were inside an object like this
Dictionary<Object, Type> dict = new Dictionary<Object, Type>();
Then I added into my dictionary an new instance object with the attributes like this
//myObject has many attributes that are empty and I just fill this 2 ones to build my dict
Object myObject = new Object();
myObject.Key1 = "A";
myObject.Key2 = "B";
dict.Add(myObject, (Type)objType);
But, the object that I want to find is loaded with data from DB and has probably many attributes filled.
The thing is when I use the TryGetValue returns nothing, so I think it's because is looking by the same reference which is not the same.
Well the question, how can I build my dictionary with 2 keys (STRING, STRING) and 1 return value (TYPE) in a easy way.
Thanks
Upvotes: 0
Views: 197
Reputation: 11860
I would use the following:
Dictionary<Tuple<string, string>, Type>
From the msdn page here:
http://msdn.microsoft.com/en-us/library/dd270346.aspx
I believe that the Equals method has been overridden for Tuple, so you should get key matching on the contents of the Tuple rather than the object reference.
Adding to dict would be:
dict.Add(new Tuple<string,string>(myObject.Key1, myObject.Key2), (Type)objType);
Upvotes: 1
Reputation: 592
Not sure what you mean by 2 keys. If you want a key containing two values, use Tuple, e.g.
Dictionary<Tuple<int, int>, string>
Another option is to use dictionary of dictionary, e.g.
Dictionary<int, Dictionary<int, string>>
Upvotes: 2