Parsing and Updating Nested Dictionaries in C#

Introduction

Hello, and welcome back! Are you ready for a new challenge? In this unit, we're stepping up to tackle a complex yet intriguing task. It involves parsing complex strings into a C# Dictionary<string, object> and then updating them, which is a common requirement in many real-world tasks. So yes, this unit's session is going to be pretty pragmatic — just the way you like it!

Task Statement

This task involves transforming a given string into a nested Dictionary<string, object> and updating a specific key-value pair within that dictionary. The input string will take the form "Key1=Value1,Key2=Value2,...". When a part of the value is another key-value string, we create a nested dictionary.

For example, the string "A1=B1,C1={D1=E1,F1=G1},I1=J1" should be transformed into the following dictionary:

Dictionary<string, object> dictionary = new Dictionary<string, object>
{
    {"A1", "B1"},
    {"C1", new Dictionary<string, string> {
        {"D1", "E1"},
        {"F1", "G1"}
    }},
    {"I1", "J1"}
};

Your C# function should parse this string into the above dictionary, then update the value of the nested key F1 from G1 to some other value, say 'NewValue'. The function should ultimately return the updated dictionary.

Step 1 - Setting Up the Function and Variables

First, set up the function and necessary variables:

using System;
using System.Collections.Generic;

public class StringParser
{
    public static Dictionary<string, object> ParseString(string inputString)
    {
        Dictionary<string, object> resultMap = new Dictionary<string, object>();

        string key = "";  // to store the current dictionary key
        Dictionary<string, string> innerMap = new Dictionary<string, string>();  // to store the inner dictionary
        bool inInnerMap = false;  // flag to check if we are inside an inner map
        int i = 0;  // to iterate through the string

Step 2 - Handling the Opening and Closing Braces

Next, handle the opening and closing braces. If an inner map is encountered, set the flag and prepare to parse it:

        while (i < inputString.Length)
        {
            if (inputString[i] == '{')
            {
                // Entering an inner map
                inInnerMap = true;
                i++; // Skip the '{'
            }
            else if (inputString[i] == '}')
            {
                // Exiting an inner map
                resultMap[key] = new Dictionary<string, string>(innerMap);
                innerMap.Clear();
                inInnerMap = false;
                i++; // Skip the '}'
                if (i < inputString.Length && inputString[i] == ',')
                {
                    i++; // Skip the ',' after '}'
                }
            } 
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal