Search code examples
c#ordereddictionary

Getting value by name from OrderedDictionary


I am looking for something like PHP's associative arrays that supports nesting too. For instance, I am creating a Dictionary Object like following:

System.Collections.Specialized.OrderedDictionary userRoles = new System.Collections.Specialized.OrderedDictionary();
userRoles["UserId"] = "120202";
userRoles["UserName"] = "Jhon Doe";

// 2D array Like
userRoles["UserRoles"][0] = "CAN_EDIT_LIST";
userRoles["UserRoles"][1] = "CAN_EDIT_PAGE";

Then I would like to access them by KeyNames instead of index values. Is it possible?


Solution

  • OrderedDictionary uses objects for both keys and values.

    To achieve nesting, just set the value to be another dictionary:

    userRoles["UserRoles"] = new Dictionary();
    

    Then you can use:

    ((Dictionary())userRoles["UserRoles"])["MyKey"] = "My Value";