我基本上是在寻找一种方法来使用c#中的二维类型键来访问哈希表值.
最终我可以做这样的事情
HashTable[1][false] = 5; int a = HashTable[1][false]; //a = 5
这就是我一直在尝试的......没有用
Hashtable test = new Hashtable(); test.Add(new Dictionary() { { 1, true } }, 555); Dictionary temp = new Dictionary () {{1, true}}; string testz = test[temp].ToString();
JaredPar.. 68
我认为更好的方法是将多维键的许多字段封装到类/结构中.例如
struct Key { public readonly int Dimension1; public readonly bool Dimension2; public Key(int p1, bool p2) { Dimension1 = p1; Dimension2 = p2; } // Equals and GetHashCode ommitted }
现在,您可以创建和使用普通的HashTable,并将此包装器用作Key.
我认为更好的方法是将多维键的许多字段封装到类/结构中.例如
struct Key { public readonly int Dimension1; public readonly bool Dimension2; public Key(int p1, bool p2) { Dimension1 = p1; Dimension2 = p2; } // Equals and GetHashCode ommitted }
现在,您可以创建和使用普通的HashTable,并将此包装器用作Key.
如何使用具有某种元组结构的常规字典作为键?
public class TwoKeyDictionary{ private readonly Dictionary , V> _dict; public V this[K1 k1, K2 k2] { get { return _dict[new Pair(k1,k2)]; } } private struct Pair { public K1 First; public K2 Second; public override Int32 GetHashCode() { return First.GetHashCode() ^ Second.GetHashCode(); } // ... Equals, ctor, etc... } }
您现在可以使用新元组在C#7.0中执行此操作:
// Declare var test = new Dictionary<(int, bool), int>(); // Add test.Add((1, false), 5); // Get int a = test[(1, false)];
以防万一有人最近在这里,如一个评论者所描述的,如何在.Net 4.0中快速而肮脏的方式这样做的例子.
class Program { static void Main(string[] args) { var twoDic = new Dictionary, String>(); twoDic.Add(new Tuple (3, true), "3 and true." ); twoDic.Add(new Tuple (4, true), "4 and true." ); twoDic.Add(new Tuple (3, false), "3 and false."); // Will throw exception. Item with the same key already exists. // twoDic.Add(new Tuple (3, true), "3 and true." ); Console.WriteLine(twoDic[new Tuple (3,false)]); Console.WriteLine(twoDic[new Tuple (4,true)]); // Outputs "3 and false." and "4 and true." } }
我想这可能更接近你正在寻找的东西......
var data = new Dictionary>();
我建议jachymko的解决方案略有不同,这将允许您避免为密钥对创建一个类.而是包装一个字典的私人字典,如下所示:
public class MultiDictionary{ private Dictionary > dict = new Dictionary >(); public V this[K1 key1, K2 key2] { get { return dict[key1][key2]; } set { if (!dict.ContainsKey(key1)) { dict[key1] = new Dictionary (); } dict[key1][key2] = value; } } }