【发布时间】:2015-01-06 19:14:12
【问题描述】:
我有一个独特的双精度对应于三个字符串的变体。我想填充字典或其他东西,以便我可以调用类似dict[key1][key2][key3] 并获取值。
我已经尝试了很多类似的东西
Dictionary<string, Dictionary<string, double>> dict = new Dictionary<string, Dictionary<string, double>> {
{ "Foo", {"Bar", 1.2 } },
{ "Foo", {"Test", 3.4 } }
};
这给了我语法错误和错误,例如“错误 4 命名空间不能直接包含字段或方法等成员”
和
Dictionary<double, Tuple<string, string>> dict = {
{1.23, "Blah", "Foo"}
};
这给了我类似“错误 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;
这给了我语法错误和错误,例如“类、结构或接口成员声明中的错误 2 无效标记 '”k1“'”
我应该怎么做?提前致谢。
![在此处输入图片描述][1]
编辑:尝试 Jonesy 的代码:
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();
}
【问题讨论】:
-
请解释如何它不起作用。如果您什么都不告诉我们,您遇到的问题很难解决。
-
感谢您的更新,但您显示的代码并未显示您声称的错误消息。
-
当我使用像
Error The contextual keyword 'var' may only appear within a local variable declaration这样的 var 时,Visual Studios 给了我错误 那也不是很理想,因为我有很多值要输入,我不想为每个值使用三行。 -
再一次,您显示的代码并未证明该问题。请显示产生您声称的错误的实际代码。
-
认真的吗?你没有找到任何其他数据结构吗?天哪,三层嵌套字典?那是一团糟。请考虑重新设计您的代码以使用更好的数据结构。
标签: c# dictionary nested multikey