mardi 1 septembre 2020

C# Call Dictionary

Is there a way to dynamically call a related Dictionary<string, string> based on a returned value?

Therefore in the example below, the value shouldBeDictionary1 returned from TestDictionary would return the value Green from Dictionary1 based on the key G passed:

private static readonly Dictionary<string, List<string>> TestDictionary = new Dictionary<string, List<string>>
{
    { "Blah", new List<string>(new[] { "Something", "Dictionary1" })},
    { "Blah, blah", new List<string>(new[] { "Something else", "Dictionary2" }) }        
};

private static readonly Dictionary<string, string> Dictionary1 = new Dictionary<string, string>
{
    { "G", "Green"},
    { "A", "Amber"},
    { "R", "Red"}
};

private static readonly Dictionary<string, string> Dictionary2 = new Dictionary<string, string>
{
    { "B", "Blue"},
    { "P", "Purple"}
};

private string Test()
{
    var shouldBeSomething = TestDictionary["Blah"][0];

    var shouldBeDictionary1 = TestDictionary["Blah"][1];

    return shouldBeDictionary1["G"] // returned value should be Green

    //MethodInfo methodInfo = typeof(Dictionary<string, string>).GetMethod(shouldBeDictionary1)
}

Attempted to use Reflection in the example above, methodInfo returns null, therefore Invoke cannot be used.

Any advice would be much appreciated.





Aucun commentaire:

Enregistrer un commentaire