c# - Parse a key1="foo",key2="bar" CSV string into a Dictionary(Of TKey, TValue) -
please take following string:
cbr="lacbtn",detnumber="1232700",laclvetype="ann=x",laccalcrun="2014-09-10",lacbutton="y",lacaccdays="0.00000000",lacentdate="2014-03-31",lactotdays="32.00",laclastent="2014-04-01",lacsrvdays="3,4",status="ok"
its output 3rd party sdk , need access values in our .net application.
what objects available in .net 2 parse string dictionary(of tkey, tvalue)
?
for instance, we'd grab values using key names, instance:
dim x = whatever("detnumber") '#### x contain "1232700"
i started coding manual stuff split on commas got messy when "," & "=" existed inside quoted values, example: key1="foo,bar",key2="hello=dorothy!"
& thought myself must exist parse type of string?
i'm not having luck finding anything.
suggestions in either vb.net or c# fine.
string rules:
the documenation bit poor (i.e. dont know how double quote within value handled yet) can confirm following:
- keys never quoted
- keys never contain spaces
- comma can exist within value:
key="hello: something"
- equals sign can exist within value:
key="something=something"
- values quoted, empty value
key=""
- one key = 1 value, key never have more 1 value
- no white space exists outside values
- keys variable , called anything, exist within values.
ok, given have strict rules around input string format, should do:
public static dictionary<string, string> getinputkeyvaluepairs(string input) { var inputkeysandvalues = new dictionary<string, string>(); if (string.isnullorwhitespace(input)) return inputkeysandvalues; const char keyvaluedelimiter = '='; const char itemdelimeter = ','; const char valuecontainer = '"'; var currentkey = string.empty; var currentvalue = string.empty; var processingkey = true; var processingvalue = false; foreach (var character in input) { if (processingkey) { // add characters currentkey until delimiter if (character == keyvaluedelimiter) processingkey = false; else currentkey += character; continue; } if (processingvalue) { // add characters currentvalue until delimeter if (character == valuecontainer) processingvalue = false; else currentvalue += character; continue; } if (character == itemdelimeter) { // we're between items now, store current key/value, reset // them empty strings, , set flag start processing key. inputkeysandvalues[currentkey] = currentvalue; currentkey = currentvalue = string.empty; processingkey = true; continue; } if (character == valuecontainer) { // we're @ first quote before value, ignore // , set flag start processing value processingvalue = true; continue; } } // add last key/value if (currentkey != string.empty) inputkeysandvalues[currentkey] = currentvalue; return inputkeysandvalues; }
Comments
Post a Comment