Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a delimted string to a dictionary<string,string> in C#

I have a string of the format "key1=value1;key2=value2;key3=value3;"

I need to convert it to a dictionary for the above mentioned key value pairs.

What would be the best way to go about this? Thanks.

like image 570
S G Avatar asked Nov 10 '10 04:11

S G


People also ask

How do I change a string to a dictionary?

To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function. Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.

What is dictionary string string in C#?

In C#, Dictionary is a generic collection which is generally used to store key/value pairs.

Can we convert list to dictionary in C#?

Convert List to Dictionary Using the Non-Linq Method in C# We can also convert a list to a dictionary in a non-LINQ way using a loop. It is advised to use the non-LINQ method because it has improved performance, but we can use either method according to our preferences.


1 Answers

Something like this?

var dict = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)                .Select(part => part.Split('='))                .ToDictionary(split => split[0], split => split[1]); 

Of course, this will fail if the assumptions aren't met. For example, an IndexOutOfRangeException could be thrown if the text isn't in the right format and an ArgumentException will be thrown if there are duplicate keys. Each of these scenarios will require different modifications. If redundant white-space could be present, you may need some string.Trim calls as necessary.

like image 65
Ani Avatar answered Sep 24 '22 17:09

Ani