If I have a string like so:
"Name=Irwin&Home=Caribbean&Preference=Coffee"
is there a method in C# that can convert that to a key-value pair similar to Request.QueryString?
If I have a string like so:
"Name=Irwin&Home=Caribbean&Preference=Coffee"
is there a method in C# that can convert that to a key-value pair similar to Request.QueryString?
You can try using HttpUtility.ParseQueryString
.
var nvc = HttpUtility.ParseQueryString(yourString);
And now, for the longest LINQ expression...
var dict = "Name=Irwin&Home=Caribbean&Preference=Coffee"
.Split('&')
.Select(p => p.Split('='))
.ToDictionary(p => p[0], p => p.Length > 1 ? Uri.UnescapeDataString(p[1]) : null);
But be aware that it will throw if there are multiple keys with the same name.
If you want to protected yourself from this add:
.GroupBy(p => p[0]).Select(p => p.First())
just before the .ToDictionary
(and after the .Select
)
this will take the first key=value
of the multiple ones. Change .First()
to .Last()
to take the last one.
You can also use the ToDictionary() method:
var input = "Name=Irwin&Home=Caribbean&Preference=Coffee";
var items = input.Split(new[] { '&' });
var dict = items.Select(item => item.Split(new[] {'='})).ToDictionary(pair => pair[0], pair => pair[1]);
You should be able to split this string based on the ampersands and equals signs, then feed each one into a new KeyValuePair:
Dictionary<string, string> myValues = new Dictionary<string,string>();
string[] elements = myString.Split('=','&');
for(int i=0;i<elements.Length; i+=2)
{
myValues.Add(elements[i], elements[i+1]);
}
This is simplistic and makes a lot of assumptions about the format of your string, but it works for your example.