Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to join Dictionary<string,string> into querystring?

Tags:

string

asp.net

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();
like image 391
Billy Avatar asked Nov 29 '22 05:11

Billy


1 Answers

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.

like image 138
grenade Avatar answered Jan 01 '23 17:01

grenade