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!

Comments
Leave a Comment