对象转字典、字典排序
【摘要】
/// <summary>
/// 将对象属性转换为key-value对
/// </summary>
/// <param name="o"></param>
/// <...
/// <summary>
/// 将对象属性转换为key-value对
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static Dictionary<String, Object> ObjToMap(Object o)
{
Dictionary<String, Object> map = new Dictionary<string, object>();
Type t = o.GetType();
PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in pi)
{
MethodInfo mi = p.GetGetMethod();
if (mi != null && mi.IsPublic)
{
map.Add(p.Name, mi.Invoke(o, new Object[] { }));
}
}
return map;
}
/// <summary>
/// 数据字典按Key升序排列
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static string DictonarySortToStr(Dictionary<string, Object> dic)
{
var dicSort = (from objDic in dic orderby objDic.Key ascending select objDic).ToList();
StringBuilder str = new StringBuilder();
for (int i = 0; i < dicSort.Count; i++)
{
KeyValuePair<string, Object> kvp = dicSort[i];
if (kvp.Value == null || string.IsNullOrEmpty(kvp.Value.ToString()))
continue;
str.AppendFormat("{0}={1}&", kvp.Key, kvp.Value);
}
str = str.Remove(str.Length - 1, 1);
return str.ToString();
}
/// <summary>
/// 数据字典按Key的Ascii升序排列
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static string DictonarySortAsciiToStr(Dictionary<string, Object> dic)
{
string[] keys = dic.Keys.ToArray();
Array.Sort(keys, string.CompareOrdinal);
StringBuilder str = new StringBuilder();
foreach (string key in keys)
{
Object value;
dic.TryGetValue(key, out value);
if (value == null || string.IsNullOrEmpty(value.ToString()))
continue;
str.AppendFormat("{0}={1}&", key, value);
}
str = str.Remove(str.Length-1,1);
return str.ToString();
}
/// <summary>
/// 数据字典按Key的Ascii升序排列
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
public static Dictionary<string, Object> DictonarySortAscii(Dictionary<string, Object> dic)
{
string[] keys = dic.Keys.ToArray();
Array.Sort(keys, string.CompareOrdinal);
Dictionary<string, Object> newDic = new Dictionary<string, Object>();
foreach (string key in keys)
{
Object value;
dic.TryGetValue(key, out value);
newDic.Add(key, value);
}
return newDic;
}
/// <summary>
/// 分隔&符号链接的字符串
/// </summary>
/// <param name="dataStr"></param>
/// <returns></returns>
public static Dictionary<string, string> SplitAndToDic(string dataStr)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
string[] strList = dataStr.Split('&');
foreach(string str in strList)
{
string[] kvStr = str.Split('=');
dic.Add(kvStr[0],kvStr[1]);
}
return dic;
}
文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。
原文链接:zzzili.blog.csdn.net/article/details/76439149
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)