Я пошел с решением, предложенным DSO (ответил 2 августа 2011 года в 7:29), его решение не требует использования HttpUtility. Однако, согласно статье, опубликованной в Dotnetpearls , использование Словаря быстрее (по производительности), чем использование NameValueCollection. Вот решение DSO, модифицированное для использования Словаря вместо NameValueCollection.
public static Dictionary QueryParametersDictionary()
{
var dictionary = new Dictionary();
dictionary.Add("name", "John Doe");
dictionary.Add("address.city", "Seattle");
dictionary.Add("address.state_code", "WA");
dictionary.Add("api_key", "5352345263456345635");
return dictionary;
}
public static string ToQueryString(Dictionary nvc)
{
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (KeyValuePair pair in nvc)
{
if (!first)
{
sb.Append("&");
}
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value));
first = false;
}
return sb.ToString();
}