如何定义&;跨多个命名空间访问嵌套字典数据C#

如何定义&;跨多个命名空间访问嵌套字典数据C#,c#,dictionary,C#,Dictionary,我有以下数据,我想以一种优雅的方式定义并快速访问 Dictionary<string, string> myDictionary = new Dictionary<string, string> { {"a", "1"}, {"b" "2"} }; 字典myDictionary=新字典 { {“a”,“1”}, {“b”“2”} }; 现在“1”和“2”在两个不同的模块x和y中定义。 我在考虑嵌套字典。我在寻找优雅的定义方式 我的想法是: //

我有以下数据,我想以一种优雅的方式定义并快速访问

Dictionary<string, string> myDictionary =  new Dictionary<string, string>
{
   {"a", "1"},
   {"b"  "2"}
};
字典myDictionary=新字典
{
{“a”,“1”},
{“b”“2”}
};
现在“1”和“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
//FileA-Namespace1
字典dcA=新字典
{
{“LOC1”,“ADDR1”},
{“LOC2”,“ADDR2”}
};
//FileB-名称空间1
字典dcB=新字典
{
{“LOC3”,“ADD3”},
{“LOC4”,“ADD4”}
};
//FileX-命名空间2
静态字典dc1=新字典
{
{“LOC1”,dcA.GetValue(“LOC1”},
{“LOC2”,dcA.GetValue(“LOC2”},
{“LOC3”,dcA.GetValue(“LOC3”},
{“LOC4”,dcA.GetValue(“LOC4”},
};
字符串myString;
字符串key=“LOC1”;
if(!dc1.TryGetValue(key,out myString))
{
抛出新的InvalidDataException(“找不到此LOC的地址”);
}
WriteLine(“myString:{0}”,myString)
//预期产出为
myString:ADDR1

是的,我想将2个字典合并成一个新字典。问题是我可以访问新字典的值,如dcA.GetValue(“LOC1”)。尝试看看是否有更好的解决方案或数据结构,我根本没有考虑过。您可以通过2个选项来实现这一点

备选案文1。 //FileX-命名空间2

Dictionary<string, string> dc1 = dcA;

foreach (var item in dcB)
{ 
    dc1[item.Key] = item.Value;     
}
字典dc1=dcA;
foreach(dcB中的var项目)
{ 
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;
}
Dictionary dc1=newdictionary();
foreach(dcA中的var项目)
{
dc1[item.Key]=item.Value;
}
foreach(dcB中的var项目)
{
dc1[item.Key]=item.Value;
}

选项1将比选项2快。因为在选项1中,在初始化期间只有一个for循环和选项copy 1st Dictionary。

我不完全确定您在这里问的是什么。所以您想将Namespace1中的Dictionary A和B合并到Namespace2中的一个新Dictionary中吗?是的,我想将2个Dictionary合并到一个新Dictionary中。问题出在哪里我可以访问新字典的值,比如dcA.GetValue(“LOC1”}。尝试看看是否有更好的解决方案或数据结构,我根本没有考虑。我不确定您如何推荐“选项1”,因为OP没有指定是否可以修改源字典。