如何使用三个键创建和填充嵌套字典
How to create and populate a nested dictionary with three keys
我有一个独特的双精度对应三个字符串的变体。我想填充字典或其他东西,这样我就可以调用 dict[key1][key2][key3]
之类的东西并获取值。
我试过很多东西,比如
Dictionary<string, Dictionary<string, double>> dict = new Dictionary<string, Dictionary<string, double>> {
{ "Foo", {"Bar", 1.2 } },
{ "Foo", {"Test", 3.4 } }
};
这给我语法错误和 "Error 4 A namespace cannot directly contain members such as fields or methods"
这样的错误
和
Dictionary<double, Tuple<string, string>> dict = {
{1.23, "Blah", "Foo"}
};
这给了我像 "Error 1 Can only use array initializer expressions to assign to array types. Try using a new expression instead."
这样的错误
和
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;
这给我语法错误和 class、结构或接口成员声明中的 "Error 2 Invalid token '"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();
}
你的最后一次尝试很接近,你想要:
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;
你想要 var
而不是 object
(或者 Dictionary<string, Dictionary<string, Dictionary<string, double>>>
如果你喜欢滚动)
最后一个字符串应该是 double
。
据我了解,您有数据并想在其中执行查找。为什么不能为此目的使用一些数据库?
但是如果你真的想硬编码所有值,你可以。只是不要手动初始化字典,进行简化 - 在运行时解析数据。
像这样。 (我想,你是 c# 编程的新手,所以为了方便起见,我创建了新的控制台应用程序并复制粘贴了所有代码)
public class Program
{
// harcode all data as string
const string RawData =
"k11,k12,k13=3.4;" +
"k21,k22,k23=4.42;" +
"k31,k32,k33=5.91;" +
"k41,k42,k43=8.14;" +
"k51,k52,k53=4.13;" +
"k61,k62,k63=5.4";
static void Main(string[] args)
{
// create dictionary from hardcoded string
var data = ParseData();
// use Tuple as key for data lookup
var value = data[Tuple.Create("k11", "k12", "k13")];
// check, that value equals expected one
Debug.Assert(value == 3.4);
}
private static IDictionary<Tuple<string, string, string>, double> ParseData()
{
var parsedData =
RawData
.Split(';')
.Select(ParseRow)
.ToDictionary(x => x.Item1, x => x.Item2);
return parsedData;
}
private static Tuple<Tuple<string, string, string>, double> ParseRow(string row)
{
var parts = row.Split('=');
var coefficients = ParseCoefficients(parts[0]);
var value = Double.Parse(parts[1], CultureInfo.InvariantCulture);
return Tuple.Create(coefficients, value);
}
private static Tuple<string, string, string> ParseCoefficients(string row)
{
var coeffs = row.Split(',');
var result = Tuple.Create(coeffs[0], coeffs[1], coeffs[2]);
return result;
}
}
作为另一种简化,您可以使用自定义 class 作为字典键而不是嵌套字典。编写你自己的(注意,它应该覆盖相等成员 Equals
和 GetHashCode
),或者使用基础 class 库中的东西。 Tuple<string, string, string>
是最完美的。
我有一个独特的双精度对应三个字符串的变体。我想填充字典或其他东西,这样我就可以调用 dict[key1][key2][key3]
之类的东西并获取值。
我试过很多东西,比如
Dictionary<string, Dictionary<string, double>> dict = new Dictionary<string, Dictionary<string, double>> {
{ "Foo", {"Bar", 1.2 } },
{ "Foo", {"Test", 3.4 } }
};
这给我语法错误和 "Error 4 A namespace cannot directly contain members such as fields or methods"
这样的错误和
Dictionary<double, Tuple<string, string>> dict = {
{1.23, "Blah", "Foo"}
};
这给了我像 "Error 1 Can only use array initializer expressions to assign to array types. Try using a new expression instead."
这样的错误和
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;
这给我语法错误和 class、结构或接口成员声明中的 "Error 2 Invalid token '"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();
}
你的最后一次尝试很接近,你想要:
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;
你想要 var
而不是 object
(或者 Dictionary<string, Dictionary<string, Dictionary<string, double>>>
如果你喜欢滚动)
最后一个字符串应该是 double
。
据我了解,您有数据并想在其中执行查找。为什么不能为此目的使用一些数据库?
但是如果你真的想硬编码所有值,你可以。只是不要手动初始化字典,进行简化 - 在运行时解析数据。
像这样。 (我想,你是 c# 编程的新手,所以为了方便起见,我创建了新的控制台应用程序并复制粘贴了所有代码)
public class Program
{
// harcode all data as string
const string RawData =
"k11,k12,k13=3.4;" +
"k21,k22,k23=4.42;" +
"k31,k32,k33=5.91;" +
"k41,k42,k43=8.14;" +
"k51,k52,k53=4.13;" +
"k61,k62,k63=5.4";
static void Main(string[] args)
{
// create dictionary from hardcoded string
var data = ParseData();
// use Tuple as key for data lookup
var value = data[Tuple.Create("k11", "k12", "k13")];
// check, that value equals expected one
Debug.Assert(value == 3.4);
}
private static IDictionary<Tuple<string, string, string>, double> ParseData()
{
var parsedData =
RawData
.Split(';')
.Select(ParseRow)
.ToDictionary(x => x.Item1, x => x.Item2);
return parsedData;
}
private static Tuple<Tuple<string, string, string>, double> ParseRow(string row)
{
var parts = row.Split('=');
var coefficients = ParseCoefficients(parts[0]);
var value = Double.Parse(parts[1], CultureInfo.InvariantCulture);
return Tuple.Create(coefficients, value);
}
private static Tuple<string, string, string> ParseCoefficients(string row)
{
var coeffs = row.Split(',');
var result = Tuple.Create(coeffs[0], coeffs[1], coeffs[2]);
return result;
}
}
作为另一种简化,您可以使用自定义 class 作为字典键而不是嵌套字典。编写你自己的(注意,它应该覆盖相等成员 Equals
和 GetHashCode
),或者使用基础 class 库中的东西。 Tuple<string, string, string>
是最完美的。