Jan
30
2010

Creating query strings with LINQ



Comments available as RSS 2.0

While implementing a recipe search API for ChickenPing, I’ve just spotted the following hilariously verbose piece of code which concatenates parameters as part of a GET request.

StringBuilder buffer = new StringBuilder();
bool first = true;
foreach(KeyValuePair<string, string> parameter in parameters) {
    if(first) {
        first = false;
    } else {
        buffer.Append('&');
    }
    if(encodeParams) {
        buffer.AppendFormat("{0}={1}", System.Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value));
    } else {
        buffer.AppendFormat("{0}={1}", parameter.Key, parameter.Value);
    }
}
string queryString = buffer.ToString();

The worst thing is I only wrote this about six months ago. I simplified it to the following with LINQ:

string queryString = parameters.Aggregate("", (allParameters, param) => allParameters + encodeParams ? 
                string.Format("{0}={1}", Uri.EscapeDataString(param.Key), Uri.EscapeDataString(param.Value)) :
                string.Format("{0}={1}", param.Key, param.Value));

One less skeleton in ChickenPing’s closet and 12 fewer lines of source code!

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment

Powered by WP Hashcash