.netframeworks

How to convert ; separated string with Key=Value into a KeyValue pair in .net?


How can i split the following string into Key-Value Pair / Hash table ...

"Id=1000;Name=xyzabc;DB=1.2.3.4;DBUserName=admin;DBPassword"

I know it can be done by using string.Split() (One with ';', and then each result with '='). I am looking for an easy and efficient way of doing it.

In short, instead of string manipulation is there an efficient way to convert the above highlighted text to access the value something like this...

someObject["Id"];//It should return 1000 
someObject["Name"];//It should return xyzabc 
someObject["DB"];//It should return xyzabc ..............

Does framework has any build in class to do it?

eg: The SQLConnectionBuilder will split the DBName, UserName, Password into its property, if we assign a connectionstring to the SQLConnectionBuilder


Solution

  • Taking your example about DbConnectionStringBuilder, if you look at the internals you'll find a method called DbConnectionOptions.GetKeyValuePair and it is not for the faint of heart. Skip that, and try something easy:

    string input = "Id=1000;Name=xyzabc;DB=1.2.3.4;DBUserName=admin;DBPassword";
    
    var kvp = input.Split(';')
        .Select(s => s.Split('=', 2))
        .ToDictionary(s => s.First(), s => s.Last());
    

    You'll get a Dictionary<string, string> output that looks something like this:

    Key=Id, Value=1000
    Key=Name, Value=xyzabc
    Key=DB, Value=1.2.3.4
    Key=DBUserName, Value=admin
    Key=DBPassword, Value=DBPassword
    

    Of course, if you have duplicate keys in your string then a dictionary won't work. You might consider writing your own extension like .ToKeyValuePair(). I'm not quite sure about how to fix the key = value when you don't provide a value, but I'm too tired to think very hard about it.