Example #1
0
        /// <summary>
        /// 将字符串型字典转换为url型字符
        /// </summary>
        /// <param name="dic">待处理字典.</param>
        /// <param name="encoding">编码方式.</param>
        /// <param name="filterEmpty">是否过滤空值.</param>
        /// <returns>String</returns>
        /// <remarks>
        ///   <list>
        ///    <item><description>添加对字符串字典转换 added by xiepeng 2018/9/20</description></item>
        ///   </list>
        /// </remarks>
        public static string ToLinkString(this Dictionary <string, string> dic, bool filterEmpty = false, string encoding = "")
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                foreach (KeyValuePair <string, string> temp in dic)
                {
                    object val = temp.Value;
                    if ((!filterEmpty && val != null) || (filterEmpty && !string.IsNullOrWhiteSpace(Utils.ToString(val))))
                    {
                        if (!string.IsNullOrEmpty(encoding))
                        {
                            Encoding encoder = Encoding.GetEncoding(encoding);
                            sb.Append(temp.Key + "=" + HttpUtility.UrlEncode(val.ToString(), encoder) + "&");
                        }
                        else
                        {
                            sb.Append(temp.Key + "=" + temp.Value + "&");
                        }
                    }
                }

                if (sb.ToString().EndsWith("&"))
                {
                    sb.Remove(sb.Length - 1, 1);
                }
            }
            catch (Exception ex)
            {
                new ECFException(ex);
            }

            return(sb.ToString());
        }