我正在 c# 中搜索一个构造,其中字典包含要计数的字典n
。我想将字典列表放入其中并建立某种索引。
我想调用它,就像dic[key][key2][key3]
值是对象或字典或包含更多字典的字典一样。
我认为弹性可以提供类似的东西,但我们的解决方案是一个独立的客户端应用程序。
我正在 c# 中搜索一个构造,其中字典包含要计数的字典n
。我想将字典列表放入其中并建立某种索引。
我想调用它,就像dic[key][key2][key3]
值是对象或字典或包含更多字典的字典一样。
我认为弹性可以提供类似的东西,但我们的解决方案是一个独立的客户端应用程序。
字典可以这样嵌套:
var dictionary = new Dictionary<string, Dictionary<string, int>>();
初始化嵌套字典:
var dictionary = new Dictionary<string, Dictionary<string, int>>
{
{ "a1", new Dictionary<string, int> { { "b1a", 1 }, { "b1b", 2 } } },
{ "a2", new Dictionary<string, int> { { "b2a", 3 }, { "b2b", 4 } } }
};
然后你像这样索引到字典中:
int x = dictionary["a1"]["b1a"];
Assert.AreEqual(1, x);
编辑:要具有任意深度,您需要创建自己的具有内置嵌套的类型,例如,
class Node
{
public int Value { get; set; }
public Dictionary<string, Node> Children { get; set; }
// The indexer indexes into the child dictionary.
public Node this[string key] => Children[key];
}
通常我会将孩子定义为列表,但您需要字典。
示例用法:
var node = new Node
{
Children = new Dictionary<string, Node>
{
{ "a1", new Node
{
Children = new Dictionary<string, Node>
{
{ "b1a", new Node { Value = 1 } },
{ "b1b", new Node { Value = 2 } }
}
}
},
{ "a2", new Node
{
Children = new Dictionary<string, Node>
{
{ "b2a", new Node { Value = 3 } },
{ "b2b", new Node { Value = 4 } }
}
}
}
}
};
int y = node["a1"]["b1a"].Value;
Assert.AreEqual(1, y);
这可以深入到你喜欢的深度——只需将另一个 Dictionary 插入叶节点的 Children 属性。