Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to use a Dictionary to reference other Dictionaries?

Tags:

c#

dictionary

Based on what I have read elsewhere it appears the general advice is to use a Dictionary to dynamically access variable/objects and other dictionaries... however I seem to be missing something simple for the last case as I can not see how to get this to work. Basically I have multiple dictionaries of data and I wish to use the value in a variable to point to the appropriate dictionary and read its data:

//----------------------------------------------------------------------------------------

// reference dictionary - pass LangID string to reference appropriate dictionary

public static Dictionary<string, dynamic> myDictionaries = new Dictionary<string, dynamic>()

{

  { "EN", "EN_Dictionary" },

  { "FR", "FR_Dictionary" },

  { "DE", "DE_Dictionary" }

};

//----------------------------------------------------------------------------------------

public static Dictionary<string, string> EN_Dictionary = new Dictionary<string, string>()

// EN language dictionary

{

  { "str1", "Some text in EN" },

  { "str2", "Some text in EN" },

  { "str3", "Some text in EN" }

};

//----------------------------------------------------------------------------------------

public static Dictionary<string, string> FR_Dictionary = new Dictionary<string, string>()

// FR language dictionary

{

  { "str1", "Some text in FR" },

  { "str2", "Some text in FR" },

  { "str3", "Some text in FR" }

};

//----------------------------------------------------------------------------------------

public static Dictionary<string, string> DE_Dictionary = new Dictionary<string, string>()

// DE language dictionary

{

  { "str1", "Some text in DE" },

  { "str2", "Some text in DE" },

  { "str3", "Some text in DE" }

};

//----------------------------------------------------------------------------------------

LangID = "DE";

//... but now what do I do ???

like image 521
Some Bad Examples Avatar asked Dec 08 '22 11:12

Some Bad Examples


1 Answers

are you asking how to access the dictionaries? It would be as follows:

var text = myDictionaries["EN"]["str1"];

And you need to define your dictionaries like this:

public static Dictionary<string, string> EN_Dictionary = ...etc;
public static Dictionary<string, string> FR_Dictionary  = ...etc;
public static Dictionary<string, string> DE_Dictionary = ...etc;
public static Dictionary<string, Dictionary<string, string>> myDictionaries 
    = new Dictionary<string, Dictionary<string, string>>()
    {
        { "EN", EN_Dictionary },
        { "FR", FR_Dictionary },
        { "DE", DE_Dictionary }
    };
like image 55
Tim Rutter Avatar answered May 22 '23 08:05

Tim Rutter