码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-09-09 11:43:09      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:

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字符串

标签:

原文地址:http://www.cnblogs.com/lowy/p/5855640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!