Is converting a NameValueCollection to a querystring using a c# lambda efficient?

前端 未结 3 1017
臣服心动
臣服心动 2021-02-20 14:59

In researching how to convert a NameValueCollection to a querystring, I have come across different methods. I am curious if the shorter lambda syntax is as efficient as it coul

3条回答
  •  醉梦人生
    2021-02-20 15:19

    I would do it like this:

    public static string ConstructQueryString(NameValueCollection parameters)
    {
        var sb = new StringBuilder();
    
        foreach (String name in parameters)
            sb.Append(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name]), "&"));
    
        if (sb.Length > 0)
            return sb.ToString(0, sb.Length - 1);
    
        return String.Empty;
    } 
    

    This way you create less objects (that have to be cleaned up by the garbage collector)

提交回复
热议问题