0

I have the below code which works fine to split a string and save key value pairs into a dictionary. Is there a more elegant and efficient way to do the same? Thank you!

    private void SplitString()
    {
        string testConfig = "application?test1=value1&test2=value2&test3=value3";

        var dict = new Dictionary<string, string>();

        if (!string.IsNullOrEmpty(testConfig) && testConfig.Contains("?"))
        {
            string parameters = testConfig.Substring(testConfig.LastIndexOf("?") + 1);

            string[] parameterArray = parameters.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            if (parameterArray.Length > 0)
            {
                foreach (var item in parameterArray)
                {
                    string[] param = item.Split(new char[] { '=' });

                    if (param.Length == 2)
                    {
                        switch (param[0].ToUpper())
                        {
                            case "TEST1":
                                dict.Add("TEST1", param[1]);
                                break;
                            case "TEST2":
                                dict.Add("TEST2", param[1]);
                                break;
                            case "TEST3":
                                dict.Add("TEST3", param[1]);
                                break;
                        }
                    }
                }
            }
        }
    }
Jyina
  • 2,530
  • 9
  • 42
  • 80
  • 2
    Yes. `var dict = HttpUtility.ParseQueryString(testConfig)`. – Yeldar Kurmangaliyev Aug 14 '19 at 18:51
  • 1
    If you are parsing a URL or a URL-encoded tag/value pair list, I *strongly* recommend you use a proven tool. This problem is harder than it looks. Remember, there are special characters, delimiters, and escape sequences to worry about, and even potential injection threats. – John Wu Aug 14 '19 at 18:57

1 Answers1

1

It looks like you are trying to split a query string into a dictionary of query parameters. You should be able to use the HttpUtility.ParseQueryString method. Note that this method returns a NameValueCollection. That object will probably work for you, but if you need a Dictionary, you can use a simple for loop to convert the NameValueCollection to a Dictionary.

Also, if you decide for whatever reason to stick with your original code, you can greatly simplify this code:

switch (param[0].ToUpper())
{
    case "TEST1":
        dict.Add("TEST1", param[1]);
        break;
    case "TEST2":
        dict.Add("TEST2", param[1]);
        break;
    case "TEST3":
        dict.Add("TEST3", param[1]);
        break;
}

You don't need a separate case for each possible value. Instead, you can simply write this:

dict.Add(param[0].ToUpper(), param[1]);
srk
  • 1,625
  • 1
  • 10
  • 26