Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming the input string is in a specific format, such as JSON, XML or a custom format, you can use a library such as Newtonsoft.Json or System.Xml to parse the string into a dynamic object or XmlDocument respectively. Once you have the parsed object, you can use recursion to convert it into the desired nested Dictionary. Here is an example implementation:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;

public Dictionary<string, object> StringToNestedDictionary(string input)
{
    var parsedObject = JObject.Parse(input);
    var nestedDict = new Dictionary<string, object>();

    foreach (var property in parsedObject.Properties())
    {
        var value = property.Value;
        if (value is JValue) // base case, value is a string
        {
            nestedDict[property.Name] = new List<string>() { value.Value<string>() };
        }
        else // recursive case, value is a nested object
        {
            nestedDict[property.Name] = StringToNestedDictionary(value.ToString());
        }
    }

    return nestedDict;
}

This implementation assumes that the input string is in JSON format, but the logic can be adapted to other formats by changing the parsing library and the types used in the implementation.