/// <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;
}