Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Created March 19, 2014 14:03
Show Gist options
  • Save sandcastle/9642282 to your computer and use it in GitHub Desktop.
Save sandcastle/9642282 to your computer and use it in GitHub Desktop.
Simple query string builder for clients.
public class QueryStringBuilder : NameValueCollection
{
public QueryStringBuilder()
: base(StringComparer.InvariantCultureIgnoreCase) { }
public QueryStringBuilder(NameValueCollection collection)
: base(StringComparer.InvariantCultureIgnoreCase)
{
Add(collection);
}
public QueryStringBuilder(object items)
: base(StringComparer.InvariantCultureIgnoreCase)
{
if (items != null)
{
foreach (var propertyInfo in items.GetType().GetProperties())
{
base.Add(
propertyInfo.Name,
(propertyInfo.GetValue(items, null) ?? "").ToString());
}
}
}
public override string ToString()
{
var builder = new StringBuilder();
var first = true;
foreach (var item in AllKeys)
{
builder.AppendFormat("{0}{1}={2}",
first ? "?" : "&",
Uri.EscapeUriString(item),
Uri.EscapeUriString(this[item]));
first = false;
}
return builder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment