MultikeyDictionary

 Hello,

 

I've tried to use a three way dicrionary, and I found a simple solution for it.

 

I needed a dictionary with 2 keys and a value, and using dictionary<KeyValuePair<>> seemed wrong.

 

I wanted something like so:

dict[1,"1"] = false
dict[2,"1"] = true
dict[10000, "something else"] = true

 

At the start I tried to build a class with dictionary to dictionary member, it was hard to maintain.

But what was seemed wrong actualy was realy right 

 

I inherited from Dictionary<KeyValuePair<K1, K2>, V> and extended the class with indexer, add & remove.

 

public class MultikeyDictionary<K1, K2, V> : Dictionary<KeyValuePair<K1, K2>, V>
{
    public V this[K1 index1, K2 index2]
    {
        get
        {
            return this[new KeyValuePair<K1, K2>(index1, index2)];
        }
        set
        {
            this[new KeyValuePair<K1, K2>(index1, index2)] = value;
        }
    }

    public bool Remove(K1 index1, K2 index2)
    {
        return base.Remove(new KeyValuePair<K1,K2>(index1, index2));
    }

    public void Add(K1 index1, K2 index2, V value)
    {
        base.Add(new KeyValuePair<K1, K2>(index1, index2), value);
    }
}

 

and I also create a 4 way dictionary using the same:

public class MultikeyDictionary<K1, K2, K3, V> : MultikeyDictionary<KeyValuePair<K1, K2>, K3, V>
{
    public V this[K1 index1, K2 index2, K3 index3]
    {
        get
        {
            return base[new KeyValuePair<K1, K2>(index1, index2), index3];
        }
        set
        {
            base[new KeyValuePair<K1, K2>(index1, index2), index3] = value;
        }
    }

    public bool Remove(K1 index1, K2 index2, K3 index3)
    {
        return base.Remove(new KeyValuePair<K1, K2>(index1, index2), index3);
    }

    public void Add(K1 index1, K2 index2, K3 index3, V value)
    {
        base.Add(new KeyValuePair<K1, K2>(index1, index2), index3, value);
    }
}

 

 

Enjoy,

Ofir

 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com