![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
///
<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 ++ ;
}
}