i have a problem with Dictionary, hope you’ll help me.
I have the following declaration:
class MainCollection<TKey1, TKey2, TValue> : Dictionary<KeyValuePair<TKey1, TKey2>, TValue>
The problem is that i cant get an element from this dictionary by TKey1 OR TKey2.
Is there a way to get an element only by TKey1 OR TKey2, not TKey1 AND TKey2?
I wrote the following code:
public TValue GetItemByKey1(TKey1 key)
{
MainCollection<int, int, string> Coll = new MainCollection<int, int, string>();
var value = from s in Coll where s.Key.Key == key select s.Value;
}
But it already has two issues:
- Compilation error: s.Key.Key == key => operator == can not be applied to types int and TKey1
- It looks ugly. Even if compilation would be successful I’m not sure that this is the fastest way to get such items. I guess that Dictionary should something better.
How can i solve such errors? I didnt find any related questions here.
Thanks in advance!
Okay, so you want to be able to lookup by
TKey1orTKey2. Then what you want is three dictionaries, one for each of the keys, and then one for the key-pairs.Note that only lookup by
(TFirstKey, TSecondKey)is unique, so you needGetByFirstKeyandGetBySecondKeyto return collections.I’ll leave the rest of the details to you.
The point is that if you want fast lookups on either key, you need two dictionaries (one for each coordinate of the key-pair). Using one can be made to work by querying the key set, but that’s slow (it’s linear to search the keys).