代码
/// <summary>
/// 对实体类进行排序
/// </summary>
/// <typeparam name="T">实体类型,如:User</typeparam>
/// <param name="list">实体类的数组</param>
/// <param name="order">排序字段(必须为属性)</param>
/// <param name="asc">是否按正序排序</param>
public static void Sort<T>(object[] list, string order, bool asc)
{
Type type = typeof(T);
PropertyInfo[] pros = type.GetProperties();
PropertyInfo pro = pros[0];
order = order.ToLower();
for (int i = 0; i < pros.Length; i++)
{
if (pros[i].Name.ToLower().Equals(order))
{
pro = pros[i];
break;
}
}
object obj;
int j, k = 1;
bool done = false;
int len = list.Length;
while (k < len && !done)
{
done = true;
for (j = 0; j < len - k; j++)
{
int b = pro.GetValue(list[j], null).ToString().CompareTo(pro.GetValue(list[j + 1], null).ToString());
if ((asc && b > 0) || (!asc && b < 0))
{
done = false;
obj = list[j];
list[j] = list[j + 1];
list[j + 1] = obj;
}
}
k++;
}
}
/// 对实体类进行排序
/// </summary>
/// <typeparam name="T">实体类型,如:User</typeparam>
/// <param name="list">实体类的数组</param>
/// <param name="order">排序字段(必须为属性)</param>
/// <param name="asc">是否按正序排序</param>
public static void Sort<T>(object[] list, string order, bool asc)
{
Type type = typeof(T);
PropertyInfo[] pros = type.GetProperties();
PropertyInfo pro = pros[0];
order = order.ToLower();
for (int i = 0; i < pros.Length; i++)
{
if (pros[i].Name.ToLower().Equals(order))
{
pro = pros[i];
break;
}
}
object obj;
int j, k = 1;
bool done = false;
int len = list.Length;
while (k < len && !done)
{
done = true;
for (j = 0; j < len - k; j++)
{
int b = pro.GetValue(list[j], null).ToString().CompareTo(pro.GetValue(list[j + 1], null).ToString());
if ((asc && b > 0) || (!asc && b < 0))
{
done = false;
obj = list[j];
list[j] = list[j + 1];
list[j + 1] = obj;
}
}
k++;
}
}