ser*_*0ne 2 .net c# collections dictionary
.NET Dictionary<TKey, TValue>对象允许分配键/值,如下所示:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["1"] = "foo";
dict["2"] = "bar";
Run Code Online (Sandbox Code Playgroud)
但我不能像这样使用字典:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict["F1"]["F2"]["F3"] = "foo";
dict["2"]["X"] = "bar";
Run Code Online (Sandbox Code Playgroud)
.NET中有一个允许我嵌套的集合[],还是我必须创建自己的集合?
如果我必须创建自己的,我该怎么做?
编辑:
如果我可以实现期望唯一键的实现也是有用的,如下所示:
dict["F1"]["F2"]["F3"] = "foo";
dict["F1"]["F2"]["F3"] = "bar"; //result is "bar" because "foo" was overridden
Run Code Online (Sandbox Code Playgroud)
以及可以多次使用密钥的实现
dict["F1"]["F2"]["F3"] = "foo";
dict["F1"]["F2"]["F3"] = "bar"; //result can be "foo" and "bar"
Run Code Online (Sandbox Code Playgroud)
这可能吗?
编辑(根据Jon Skeet的提问):
我想使用这样的结构(作为一个非常粗略的例子):
json["data"]["request"]["name"] = "username";
json["data"]["request"]["pass"] = "password";
Run Code Online (Sandbox Code Playgroud)
解决了
{ data: { request: { name: "username", pass: "password" } } }
Run Code Online (Sandbox Code Playgroud)
并且同样会有XML等效的等价物.
ser*_*0ne 15
根据我的测试,我已经提出了以下解决方案,据我所知,这个解决方案没有中断.
public class NestedDictionary<K, V> : Dictionary<K, NestedDictionary<K, V>>
{
public V Value { set; get; }
public new NestedDictionary<K, V> this[K key]
{
set { base[key] = value; }
get
{
if (!base.Keys.Contains<K>(key))
{
base[key] = new NestedDictionary<K, V>();
}
return base[key];
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
NestedDictionary<string, string> dict = new NestedDictionary<string, string>();
dict["one"].Value = "Nest level 1";
dict["one"]["two"]["three"].Value = "Nest level 3";
dict["FieldA"]["FieldB"].Value = "Hello World";
Console.WriteLine(dict["one"].Value);
Console.WriteLine(dict["one"]["two"]["three"].Value);
Console.WriteLine(dict["FieldA"]["FieldB"].Value);
Run Code Online (Sandbox Code Playgroud)
zee*_*onk 12
您可以使用标准Dictionary执行此操作,您只需声明嵌套:
Dictionary<string, Dictionary<string, string>> dict = ...
string test = dict["first"]["second"]
Dictionary<string, Dictionary<string, Dictionary<string, string>>> dict = ...
string test = dict["first"]["second"]["third"]
etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15231 次 |
| 最近记录: |