首页 > 代码库 > 通过字典给类的实体属性赋值生成url字符串

通过字典给类的实体属性赋值生成url字符串

private static Dictionary<string, string> SortedToDictionary(SortedDictionary<string, string> dicArrayPre, params string[] paras)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> temp in dicArrayPre)
if (!paras.Contains(temp.Key) && !string.IsNullOrEmpty(temp.Value))
dict.Add(temp.Key, temp.Value);
return dict;
}
private static string GetParmStr<T>(T model, bool isUrlEncode = false, params string[] paras)
{
var sortedDict = GetResultDictionary<T>(model);
var dict = FilterParams(sortedDict, paras);
return CreateLinkStringUrl(dict, isUrlEncode);
}
private static SortedDictionary<string, string> GetResultDictionary<T>(T model)
{
SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>();
List<string> paramsList = new List<string>();// 把实体类中的属性名称转换成List<string>
var modelDict = model.GetType().GetProperties().ToDictionary(a => a.Name.Substring(0, 1).ToLower() + a.Name.Substring(1));
foreach (var dkey in modelDict)
paramsList.Add(dkey.Key);

foreach (var p in paramsList)
{
System.Reflection.PropertyInfo pi = null;
if (modelDict.TryGetValue(p, out pi))
{
object obj = pi.GetValue(model, null);
if (pi != null && obj != null && !obj.ToString().Equals(""))
sortedDictionary.Add(p, obj.ToString());
}
}
return sortedDictionary;
}
private static Dictionary<string, string> FilterParams(SortedDictionary<string, string> sortedDictionary, params string[] paras)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> temp in sortedDictionary)
if (!paras.Contains(temp.Key) && !string.IsNullOrEmpty(temp.Value))
dict.Add(temp.Key, temp.Value);
return dict;
}
private static string CreateLinkStringUrl(Dictionary<string, string> dictionary, bool isUrlEncode = false)
{
StringBuilder stringBuilder = new StringBuilder();
if (isUrlEncode)
{
foreach (KeyValuePair<string, string> temp in dictionary)
stringBuilder.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value) + "&");
}
else
{
foreach (KeyValuePair<string, string> temp in dictionary)
stringBuilder.Append(temp.Key + "=" + temp.Value + "&");
}
int nLen = stringBuilder.Length;
stringBuilder.Remove(nLen - 1, 1);
return stringBuilder.ToString();
}

通过字典给类的实体属性赋值生成url字符串