Convert a Dictionary to string of url parameters?
Solution 1
One approach would be:
var url = string.Format("http://www.yoursite.com?{0}",
HttpUtility.UrlEncode(string.Join("&",
parameters.Select(kvp =>
string.Format("{0}={1}", kvp.Key, kvp.Value)))));
You could also use string interpolation as introduced in C#6:
var url = $"http://www.yoursite.com?{HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")))}";
And you could get rid of the UrlEncode
if you don't need it, I just added it for completeness.
Solution 2
Make a static helper class perhaps:
public static string QueryString(IDictionary<string, object> dict)
{
var list = new List<string>();
foreach(var item in dict)
{
list.Add(item.Key + "=" + item.Value);
}
return string.Join("&", list);
}
Solution 3
You can use QueryHelpers from Microsoft.AspNetCore.WebUtilities:
string url = QueryHelpers.AddQueryString("https://me.com/xxx.js", dictionary);
Solution 4
the most short way:
string s = string.Join("&", dd.Select((x) => x.Key + "=" + x.Value.ToString()));
But shorter does not mean more efficiency. Better use StringBuilder
and Append
method:
first = true;
foreach(var item in dd)
{
if (first)
first = false;
else
sb.Append('&');
sb.Append(item.Key);
sb.Append('=');
sb.Append(item.Value.ToString());
}
Solution 5
I'm not saying this option is better (I personally think it's not), but I'm here just to say it exists.
The QueryBuilder
class:
var queryStringDictionary = new Dictionary<string, string>
{
{ "username", "foo" },
{ "password", "bar" }
};
var queryBuilder = new QueryBuilder(queryStringDictionary);
queryBuilder.Add("type", "user");
//?username=foo&password=bar&type=user
QueryString result = queryBuilder.ToQueryString();
lko
Updated on July 26, 2022Comments
-
lko almost 2 years
Is there a way to convert a Dictionary in code into a url parameter string?
e.g.
// An example list of parameters Dictionary<string, object> parameters ...; foreach (Item in List) { parameters.Add(Item.Name, Item.Value); } string url = "http://www.somesite.com?" + parameters.XX.ToString();
Inside MVC HtmlHelpers you can generate URLs with the UrlHelper (or Url in controllers) but in Web Forms code-behind the this HtmlHelper is not available.
string url = UrlHelper.GenerateUrl("Default", "Action", "Controller", new RouteValueDictionary(parameters), htmlHelper.RouteCollection , htmlHelper.ViewContext.RequestContext, true);
How could this be done in C# Web Forms code-behind (in an MVC/Web Forms app) without the MVC helper?