mardi 10 mai 2016

C#: Dynamically access dictionary element stored as string in a variable

Is there a way to access dictionary element dynamically when the element name is stored as a string in a variable.

string field2 = "Entity[\"EmpId\"]";

I have tried accessing the string type and it works as expected but not able to understand how to get the dictionary element value dynamically. Here is what I tried so far. Demo here

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Message message = new Message();
        message.EntityId = "123456";

        message.Entity = new Dictionary<string, string>() 
        {
            { "EmpId", "987654"},
            { "DeptId", "10"}
        };

        // Dynamically accessing the field WORKS
        string field1 = "EntityId";
        var v1 = message.GetType().GetProperty(field1).GetValue(message, null); // <-- Works as expected
        Console.WriteLine("EntityId: " + v1.ToString());  // <-- Output: 123456

        // Dynamically accessing a Dictionary element DOESN'T WORK
        string field2 = "Entity[\"EmpId\"]";
        var v2 = message.GetType().GetProperty(field2).GetValue(message, null); // <-- Throws an exception
        //Console.WriteLine("Name: " + v2.ToString());  // <-- Expected Outut: 987654

        Console.WriteLine();
    }

    class Message
    {
        public string EntityId { get; set; }

        // Replacing EntityId with a Dictionary as we have more than one Entities
        public Dictionary<string, string> Entity { get; set; }
    }
}





Aucun commentaire:

Enregistrer un commentaire