Hashtable with MultiDimensional Key in C#

后端 未结 16 1353
闹比i
闹比i 2020-11-27 02:58

I\'m basically looking for a way to access a hashtable value using a two-dimensional typed key in c#.

Eventually I would be able to do something like this



        
相关标签:
16条回答
  • 2020-11-27 03:49

    I would suggest that you create a small custom class exposing the bool and int properties, and override its GetHashCode and Equals methods, then use this as the key.

    0 讨论(0)
  • 2020-11-27 03:50

    Could you use a Dictionary<KeyValuePair<int,bool>,int>?

    0 讨论(0)
  • 2020-11-27 03:53

    I think a better approach is to encapsulate the many fields of your multi-dimensional key into a class / struct. For example

    struct Key {
      public readonly int Dimension1;
      public readonly bool Dimension2;
      public Key(int p1, bool p2) {
        Dimension1 = p1;
        Dimension2 = p2;
      }
      // Equals and GetHashCode ommitted
    }
    

    Now you can create and use a normal HashTable and use this wrapper as a Key.

    0 讨论(0)
  • 2020-11-27 03:56

    I think the easiest way to do it now is to use Tupple.Create and ValueTuple.Create:

    > var k1 =  Tuple.Create("test", int.MinValue, DateTime.MinValue, double.MinValue);
    > var k2 = Tuple.Create("test", int.MinValue, DateTime.MinValue, double.MinValue);
    > var dict = new Dictionary<object, object>();
    > dict.Add(k1, "item");
    > dict.Add(k2, "item");
    An item with the same key has already been added....
    > dict[k1] == dict[k2]
    true
    

    or use new c#7 tuple syntax to create tuple-keys:

    var k = (item1: "value1", item2: 123);
    
    0 讨论(0)
提交回复
热议问题