0

I have the following data, i want to define in a elegant way and fast access.

Dictionary<string, string> myDictionary =  new Dictionary<string, string>
{
   {"a", "1"},
   {"b"  "2"}
};

Now the "1" and "2" defined in 2 different modules x and y. I'm thinking of nested dictionary here. I'm looking for elegant way to define.

My thinking:

    //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

Yes i want to combine 2 dictionary to a new dictionary. The problem is i can access value of new dictionary like this dcA.GetValue("LOC1"}. Trying to see if there a better solution or data struct which i'm not thinking at all.

  • I'm not entirely sure what you're asking here. – kkyr Oct 31 '15 at 01:00
  • So you want to combine Dictionary A & B from Namespace1 in a new Dictionary in Namespace2? – Camo Oct 31 '15 at 01:01
  • Yes i want to combine 2 dictionary to be combined in a new dictionary. The problem is i can access value of new dictionary like this dcA.GetValue("LOC1"}. Trying to see if there a better solution or data struct which i'm not thinking at all. – anotheruser Oct 31 '15 at 01:03

1 Answers1

0

You can do this by 2 options.

Option 1. //FileX - NameSpace 2

Dictionary<string, string> dc1 = dcA;

foreach (var item in dcB)
{ 
    dc1[item.Key] = item.Value;     
}

Option 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;
}

Option 1 will be faster than option 2. Because in option 1 has only one for loop and option copy 1st Dictionary during init.

kkyr
  • 3,785
  • 3
  • 29
  • 59
Jigneshk
  • 350
  • 1
  • 7