Quickly convert Comma Separated Values to Dictionary

If you are getting some sort of CSV let’s say some sort of configurations or data object or whatever the case may be, my strategy is : “If you can not deserialize ’em, structure ’em !”

And here is one of the possible scenario :


If you’re dealing with more complex scenario, you might wanna consider using Tuple or Jagged Tuple ! ( What is it ? )

using System;
using System.Collections.Generic;
namespace ConsoleApplication1

  class Program
    static void Main(string[] args)

      //assuming the string is well formatted and follows the constraints
      //this string may be a function parameter

      string strCommaSeparatedKeyValueString = "key1=value1,key2=value2,key3=value3,key4=value4,key5=value5";

      Dictionary<string, string> paramDict = new Dictionary<string, string>();
      string key = "", val = "";

      foreach (string keyval in strCommaSeparatedKeyValueString.Split(','))
        if (!string.IsNullOrEmpty(keyval) && keyval.IndexOf('=') != -1)
          key = keyval.Substring(0, keyval.IndexOf("="));
          val = keyval.Substring(keyval.IndexOf("="), (keyval.Length - keyval.IndexOf("="))).Replace("=", "");
          paramDict.Add(key, val);
          Console.WriteLine("{0} ---> {1}", key, paramDict[key]);

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s