Convert string or stringbuilder to name/value collection

N

npverni

I have a string with name value collections (i.e. &foo=1&foo2=2)

Can I convert this string to some kind of name/value collection so I
can access the values with something like :

params["foo"] = 1;

Thanks,
 
K

Kevin Spencer

Sure. You can use System.Collections.Specialized.NameValueCollection. First,
split the string into an array of strings, by splitting on the "&"character.
Then loop through the array of strings, splitting each one on the "="
character, and adding a new Item to the Collection. Example:

string source = "this=that&these=those&them=Something Else";
NameValueCollection myValues = new NameValueCollection();
string[] aryStrings = source.Split(new char[] {'&']});
string[] nameAndValue;
foreach (string s in aryStrings)
{
nameAndValue = s.Split(new char[] {'='});
myValues.Add(nameAndValue[0], nameAndValue[1]);
}

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top