问题1:
需求是将字典转化成get请求规范的字符串,
name1=value1&name2=value2&name3..
怎么写消耗最小 效率最高?
问题2:
以下两种写法有什么不同?
static public string ParseToString(IDictionary<string, string> parameters)
{
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
StringBuilder query = new StringBuilder("");
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
query.Append(key).Append("=").Append(value).Append("&");
}
}
string content = query.ToString().Substring(0, query.Length - 1);
return content;
}
static public string ParseToString(Dictionary<string, string> parameters)
{
StringBuilder query = new StringBuilder("");
foreach (var param in parameters)
if (!string.IsNullOrEmpty(param.Key) && !string.IsNullOrEmpty(param.Value))
query.Append(param.Key).Append("=").Append(param.Value).Append("&");
string content = query.ToString().Substring(0, query.Length - 1);
return content;
}