Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a string Abc = {GRFD_Id=29, GL_Id=1, CK_Id=15, CPM_Current_Float=405012.1700, CGJM_Allowed_Float=99999999.0000, WL_Name=RahnamCP, PK_Amount=750.00, GK_Name=Domestic Diamond, GP_PK_Id=51, VG_Expiry=365, CP_Name=JohnClient}

Sample from string

in GRFD_Id=29
GRFD_Id is the Key
29 is Value


now i want too the keys and values into dictionary .. how can i achieve this!
Posted
Updated 14-Jul-15 22:43pm
v2

A very brute force solution could be to use string.Split method. Something like:
C#
foreach (string element in originalstring.Split(',')) {
   myDictionary.Add(element.Split('=')[0], element.Split('=')[1]);
}
 
Share this answer
 
You might:
  • remove the heading and trailing curly braces.
  • iterate over the array obtained by splitting the remaining string using the ',' character as separator.
  • add to the dictionary the array items obtained splitting again the item, this time using the '=' character as separator.
 
Share this answer
 
C#
string Abc = "GRFD_Id=29, GL_Id=1, CK_Id=15, CPM_Current_Float=405012.1700, CGJM_Allowed_Float=99999999.0000, WL_Name=RahnamCP, PK_Amount=750.00, GK_Name=Domestic Diamond, GP_PK_Id=51, VG_Expiry=365, CP_Name=JohnClient";

//IF you simply want the string to converted into Dictionary then you can  following code.

            var Dictionary = Abc.Split(',').ToList().Select(m =>
            {
                var res = m.Split('=');
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add(res[0], res[1]);
                return dict;
            });

//and if want the first values of  string to  be converted into Dictionary then you can  following code.

            var FirstRecord = Abc.Split(',').ToList().Select(m =>
            {
                var res = m.Split('=');
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add(res[0], res[1]);
                return dict;
            }).FirstOrDefault();</pre>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900