using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
namespace YTSoft.Common
{
///
/// 排序帮助类(包括对string[],int[],datatable,T[]进行排序)
///
public class SortUtil
{
///
/// 对int数组进行排序
///
/// int数组
/// 是否按升序排列
public static void SortInt(int[] list, bool asc)
{
int 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 = list[j].CompareTo(list[j + 1]);
if ((asc && b > 0) || (!asc && b < 0))
{
done = false;
obj = list[j];
list[j] = list[j + 1];
list[j + 1] = obj;
}
}
k++;
}
}
///
/// 对string数组进行排序
///
/// string数组
/// 是否按升序排列
public static void SortString(string[] list, bool asc)
{
string 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 = list[j].CompareTo(list[j + 1]);
if ((asc && b > 0) || (!asc && b < 0))
{
done = false;
obj = list[j];
list[j] = list[j + 1];
list[j + 1] = obj;
}
}
k++;
}
}
///
/// 对datatable进行排序,返回排序后的datatable
///
/// 要排序的datatable
/// 排序字段
/// 是否升序
///
static DataTable SortDataTable(DataTable dt, string order, bool asc)
{
DataView view = dt.DefaultView;
view.Sort = string.Format("{0} {1}", order, (asc ? "asc" : "desc"));
return view.ToTable();
/*
DataRow[] rows = dt.Select("", order + " " + (asc ? "asc" : "desc"));
DataTable dt2 = dt.Clone();
foreach (DataRow row in rows)
dt2.Rows.Add(row.ItemArray);
dt.Clear();
return dt2;
*/
}
///
/// 对实体类进行排序
///
/// 实体类型,如:User
/// 实体类的数组
/// 排序字段(必须为属性)
/// 是否按正序排序
public static void Sort(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++;
}
}
}
}