一种是用系统自带的Linq语句进行排序,比使用第二种归并排序要快好几倍,推荐使用第一种方法:
其中GetTextInsertPt(x)获取cad文字对象插入点坐标的方法,在第二种排序方法里面!
第一种:Linq语句进行排序:速度快!
List<object> objEntArr = new List<object>();
objEntArr = objEntArr.OrderBy(x => MyMethod.GetTextInsertPt(x)[0]).Select(x => x).ToList();
第二种:归并排序法:速度慢!
/// <summary>
/// 按文字位置坐标排序
/// </summary>
/// <param name="lst">文字集合</param>
/// <param name="axis">对应轴的索引,默认0->X,1->Y,2->Z</param>
/// <param name="isup">升序还是降序排列,默认升序True,降序False</param>
public static void MergeSort_TextPoint(ref List<object> arylst, int axis = 0, bool isup = true)
{
object[] arr = arylst.ToArray();
MergeSort(ref arr, 0, arr.Length - 1, axis, isup);
arylst = arr.ToList();
}
/// <summary>
/// 按文字位置坐标排序
/// </summary>
/// <param name="lst">文字集合</param>
/// <param name="axis">对应轴的索引,默认0->X,1->Y,2->Z</param>
/// <param name="isup">升序还是降序排列,默认升序True,降序False</param>
public static void MergeSort_TextPoint(ref object[] arr, int axis = 0, bool isup = true)
{
MergeSort(ref arr, 0, arr.Length - 1, axis, isup);
}
private static void MergeSort(ref object[] arr, int ArrMin, int ArrMax, int axis, bool isup)
{
if (ArrMax > ArrMin)
{
int ArrMid = (ArrMin + ArrMax) / 2;
MergeSort(ref arr, ArrMin, ArrMid, axis, isup);
MergeSort(ref arr, ArrMid + 1, ArrMax, axis, isup);
Merge(ref arr, ArrMin, ArrMid, ArrMax, axis, isup);
}
}
private static void Merge(ref object[] arr, int ArrMin, int ArrMid, int ArrMax, int axis, bool isup)
{
bool result;
object[] temp = new object[ArrMax - ArrMin + 1];
int i = ArrMin;
int j = ArrMid + 1;
int k = 0;
while (i <= ArrMid && j <= ArrMax)
{
string str1 = GetTextstr((AcadObject)arr[i]);
double[] basept1 = GetTextInsertPt((AcadObject)arr[i]);
string str2 = GetTextstr((AcadObject)arr[j]);
double[] basept2 = GetTextInsertPt((AcadObject)arr[j]);
if (isup)
{
result = basept1[axis] < basept2[axis];
}
else
{
result = basept1[axis] > basept2[axis];
}
if (result)
{
temp[k] = arr[i];
k++;
i++;
}
else
{
temp[k] = arr[j];
k++;
j++;
}
}
while (i <= ArrMid)
{
temp[k] = arr[i];
k++;
i++;
}
while (j <= ArrMax)
{
temp[k] = arr[j];
k++;
j++;
}
for (k = 0, i = ArrMin; i <= ArrMax; k++, i++)
{
arr[i] = temp[k];
}
}
/// <summary>
/// 获取文字插入点坐标
/// </summary>
/// <param name="Obj">*Text object 对象</param>
/// <returns>插入点坐标</returns>
public static double[] GetTextInsertPt(object Obj)
{
if (((AcadObject)Obj).ObjectName.Equals("AcDbText"))
{
return ((AcadText)Obj).InsertionPoint;
}
else
{
return ((AcadMText)Obj).InsertionPoint;
}
}