I have following data:
Dictionary<string,string> dctParameters = new Dictionary(){
{"a",var1},{"b",var2},{"c",var3},....
}
I want to join the "dctParameters" into a querystring.
What's the fastest / best among the following ways? Can you think you of a better way to do this?
1st method:
StringBuilder data = new StringBuilder();
string result = dctParameters.Aggregate(data, (x, pair) => data.Append(pair.Key).Append("=").Append(pair.Value).Append("&")).ToString();
2nd method:
StringBuilder data = new StringBuilder();
foreach (var item in dctParameters)
{
data.Append(string.Format("{0}={1}&",item.Key, item.Value));
}
string result = data.ToString();
3rd method:
StringBuilder data = new StringBuilder();
foreach (var item in dctParameters)
{
data.Append(item.Key).Append("=").Append(item.Value).Append("&");
}
string result = data.ToString();
How about an extension method as a variation of Eric's suggestion:
public static string ToQueryString(this Dictionary<string, string> dict)
{
return '?' + string.Join("&", dict.Select(p => p.Key + '=' + p.Value).ToArray());
}
eg:
dctParameters.ToQueryString();
The performance cost of any of your implementations is really not worth losing sleep over considering that this kind of process is not likely to bog down a server. The issue is (as you say) better not faster and what you seem to be after is an elegant approach rather than the least CPU cycles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With