Creating query strings with LINQ
Leave a Comment
Posted in Programming
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(); </string>
The worst thing is I only wrote this about six months ago. I simplified it to the following with LINQ:
