.NET dictionary with two keys and one value

前端 未结 13 3023
盖世英雄少女心
盖世英雄少女心 2020-12-14 00:23

Is there a dictionary available in .NET that could hold 2 keys and one value. Like

Dictionary(Of TKey, Of TKey, TValue)

I have

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 00:43

    As a local solution I use the easy approach:

    Imagine I have a collection of products identified by a string and a form with buttons for each one of the products.

    When managing the state of the buttons I need to find buttons by string key. When handling the clicks I need to find product IDs by button instance.

    Instead of maintaining two separate dictionaries I do the following:

    public class SPurchaseOption
    {
        public Button Button;
        public string ProductID;
        public string SomeOtherAssociatedData;
    }
    
    Dictionary purchaseOptions;
    

    When the buttons are initialized I append two entries into the Dictionary i.e.

    Key: ProductID, Value: "SPurchaseOption"
    Key: Button,    Value: "SPurchaseOption"
    

    For a more general approach and if you need a commonly used component you will have to build a wrap around two dictionaries i.e:

    public class DoubleKeyedDictionary
    {
        class SItem
        {
            public TKey1 key1;
            public TKey2 key2;
            public TValue value;
        }
    
        Dictionary dic1;
        Dictionary dic2;
    }
    

    this will give access to both the value and alternative key by any of the keys.

提交回复
热议问题