Cha*_*ton 0 c# dictionary nested multikey
我有一个独特的双精度对应于三个字符串的变体。我想填充字典或其他东西,以便我可以调用类似的东西dict[key1][key2][key3]并获取值。
我尝试过很多类似的事情
Dictionary<string, Dictionary<string, double>> dict = new Dictionary<string, Dictionary<string, double>> {
{ "Foo", {"Bar", 1.2 } },
{ "Foo", {"Test", 3.4 } }
};
Run Code Online (Sandbox Code Playgroud)
这给了我语法错误和错误,例如“错误 4 命名空间不能直接包含字段或方法等成员”
和
Dictionary<double, Tuple<string, string>> dict = {
{1.23, "Blah", "Foo"}
};
Run Code Online (Sandbox Code Playgroud)
这给了我这样的错误:“错误 1 只能使用数组初始值设定项表达式来分配给数组类型。请尝试使用新的表达式。”
和
object dict = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
dict["k1"] = new Dictionary<string, Dictionary<string, string>>();
dict["k1"]["k2"] = new Dictionary<string, string>();
dict["k1"]["k2"]["k3"] = 3.5;
Run Code Online (Sandbox Code Playgroud)
这给了我语法错误和错误,例如“错误 2 类、结构或接口成员声明中的无效标记 '“k1”'”
我该怎么办?提前致谢。
![在此输入图像描述][1]

编辑:尝试琼斯的代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string[] grades = { "Grade 1", "Grade 5", "Grade 8", "ASTM A325", "316 Stainless", "Monel", "Brighton Best 1960" };
string[] sizes = { "#1", "2", "3", "4", "5", "6", "8", "10", "12", "1/4", "5/16", "3/8", "7/16", "1/2", "9/16", "5/8", "3/4", "7/8", "1", "1-1/8", "1-1/4", "1-3/8", "1-1/2" };
var dict = new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();
dict["k1"] = new Dictionary<string, Dictionary<string, double>>();
dict["k1"]["k2"] = new Dictionary<string, double>();
dict["k1"]["k2"]["k3"] = 3.5;
public Form1()
{
InitializeComponent();
}
Run Code Online (Sandbox Code Playgroud)
你的最后一次尝试已经接近,你想要:
var dict = new Dictionary<string, Dictionary<string, Dictionary<string, double>>>();
dict["k1"] = new Dictionary<string, Dictionary<string, double>>();
dict["k1"]["k2"] = new Dictionary<string, double>();
dict["k1"]["k2"]["k3"] = 3.5;
Run Code Online (Sandbox Code Playgroud)
你想要var而不是object
(或者Dictionary<string, Dictionary<string, Dictionary<string, double>>>如果你喜欢滚动)
你的最后一个字符串应该是一个double.
| 归档时间: |
|
| 查看次数: |
4066 次 |
| 最近记录: |