List to comma separated and Dictionary to Query string


List or Array to Comma separated string
Have you ever had a list or array of string that you need to show them comma separated?
Yeah, the easiest way is to iterate list and using string builder to concat them with comma .but all of us know that it is not a cool way and there should be a better way. Because it is a simple and known requirement in programming and .Net framework should have a better solution for that.

And with this method it is easy to write a method to create a query string based on dictionary.

public string ToQueryString( Dictionary<string, string> source)
        {
            return "?" + String.Join("&", source.Select(d => String.Format("{0}={1}", HttpUtility.UrlEncode(d.Key), HttpUtility.UrlEncode(d.Value))).ToArray());
        }

Comments

Unknown said…
That's useful. I prefer to use StringBuilder instead of String.Join because of the performance optimization other than that it's great.
Thanks