我有以下数据,我想用一种优雅的方式和快速访问来定义。
Dictionary<string, string> myDictionary = new Dictionary<string, string>
{
{"a", "1"},
{"b" "2"}
};
现在"1"one_answers"2"定义在两个不同的模块x和y中。我在想嵌套字典。我正在寻找优雅的定义方式。
我的想法:
//FileA - Namespace1
Dictionary<string, string> dcA = new Dictionary<string, string>
{
{"LOC1", "ADDR1"},
{"LOC2", "ADDR2"}
};
//FileB - NameSpace1
Dictionary<string, string> dcB = new Dictionary<string, string>
{
{"LOC3", "ADD3"},
{"LOC4", "ADD4"}
};
//FileX - NameSpace 2
static Dictionary<string, string> dc1 = new Dictionary<string, Dictionary<string, string>>
{
{"LOC1", dcA.GetValue("LOC1"},
{"LOC2", dcA.GetValue("LOC2"},
{"LOC3", dcA.GetValue("LOC3"},
{"LOC4", dcA.GetValue("LOC4"},
};
string myString;
string key = "LOC1";
if (!dc1.TryGetValue(key, out myString))
{
throw new InvalidDataException("Can't find the your Addr for this LOC");
}
Console.WriteLine("myString : {0}", myString)
//Expected output as
myString : ADDR1
是的,我想把两本字典合并成一本新字典。问题是我可以访问像dcA.GetValue("LOC1")这样的新字典的值。试图看看是否有更好的解决方案或数据结构,而我根本没有想到。
您可以通过两个选项来实现这一点。
选项1。//FileX-命名空间2
Dictionary<string, string> dc1 = dcA;
foreach (var item in dcB)
{
dc1[item.Key] = item.Value;
}
选项2。
Dictionary<string, string> dc1 = new Dictionary<string,string>();
foreach (var item in dcA)
{
dc1[item.Key] = item.Value;
}
foreach (var item in dcB)
{
dc1[item.Key] = item.Value;
}
选项1将比选项2更快。因为在选项1中只有一个for循环和选项copy 1st Dictionary。