Composite Key Dictionary

后端 未结 9 524
心在旅途
心在旅途 2020-12-02 10:18

I have some objects in List, let\'s say List and MyClass has several properties. I would like to create an index of the list based on 3 properti

9条回答
  •  臣服心动
    2020-12-02 10:50

    Two approaches immediately spring to mind:

    1. Do as Kevin suggested and write a struct that will serve as your key. Be sure to make this struct implement IEquatable and to override its Equals and GetHashCode methods*.

    2. Write a class that utilizes nested dictionaries internally. Something like: TripleKeyDictionary... this class would internally have a member of type Dictionary>>, and would expose methods such as this[TKey1 k1, TKey2 k2, TKey3 k3], ContainsKeys(TKey1 k1, TKey2 k2, TKey3 k3), etc.

    *A word on whether overriding the Equals method is necessary: while it's true that the Equals method for a struct compares the value of each member by default, it does so by using reflection -- which inherently entails performance costs -- and is therefore not a very appropriate implementation for something that is meant to be used as a key in a dictionary (in my opinion, anyway). According to the MSDN documentation on ValueType.Equals:

    The default implementation of the Equals method uses reflection to compare the corresponding fields of obj and this instance. Override the Equals method for a particular type to improve the performance of the method and more closely represent the concept of equality for the type.

提交回复
热议问题