110,533
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// Sort a entity array.
/// </summary>
/// <param name="orgArray">Entity array.</param>
/// <param name="isAsc">Sort order.</param>
/// <param name="orderBy">
/// An array of properties names. Must be a property in each of them,
/// and the properties comparable. Compare these properties values.
/// </param>
public static object[] Sort(object[] orgArray, bool isAsc, params string[] orderBy)
{
if (orgArray == null || orgArray.Length == 0)
return null;
sort(orgArray, 0, orgArray.Length, isAsc, orderBy);
return null;
}
/// <summary>
/// Quicksort.
/// </summary>
/// <param name="orgArray">Entity array.</param>
/// <param name="low"></param>
/// <param name="high"></param>
/// <param name="orderBy">
/// An array of properties names. Must be a property in each of them,
/// and the properties comparable. Compare these properties values.
/// </param>
private static void sort(object[] orgArray, int low, int high, bool isAsc, params string[] orderBy)
{
int i, j, f;
object t;
if (low == high)
return;
if (low == high - 1)
{
if ((Compare(orgArray[low] , orgArray[high], orderBy) < 0) == isAsc)
{
t = orgArray[low];
orgArray[low] = orgArray[high];
orgArray[high] = t;
}
return;
}
i = low;
j = high;
f = low;
while (i != j)
{
for (; j != i; j-- )
{
if ((Compare(orgArray[j], orgArray[f], orderBy) < 0) == isAsc)
{
t = orgArray[j];
orgArray[j] = orgArray[f];
orgArray[f] = t;
f = j;
break;
}
}
if (i == j) break;
for (; i != j; i++ )
{
if ((Compare(orgArray[i], orgArray[f], orderBy) < 0) == isAsc)
{
t = orgArray[i];
orgArray[i] = orgArray[f];
orgArray[f] = t;
f = i;
break;
}
}
}
if (f > low)
sort(orgArray, low, f - 1, isAsc, orderBy);
if ( f < high)
sort(orgArray, f + 1, high, isAsc, orderBy);
}
/// <summary>
/// Compare two object.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="orderBy">
/// An array of properties names. Must be a property in each of them,
/// and the properties comparable. Compare these properties values.
/// </param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects
/// being compared. The return value has these meanings: Value Meaning Less than
/// zero This instance is less than obj. Zero This instance is equal to obj.
/// Greater than zero This instance is greater than obj.
/// </returns>
private static int Compare(object a, object b, params string[] orderBy)
{
Type type = a.GetType();
PropertyInfo pro = null;
foreach (string proname in orderBy)
{
pro = type.GetProperty(proname);
if (!pro.GetValue(a, null).Equals(pro.GetValue(b, null)))
{
return ((IComparable)pro.GetValue(a, null)).CompareTo(pro.GetValue(b, null));
}
}
return 0;
}