欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现对二维数组排序的方法

程序员文章站 2023-10-24 08:01:17
本文实例讲述了c#实现对二维数组排序的方法。分享给大家供大家参考。具体实现方法如下: /// /// a generic rou...

本文实例讲述了c#实现对二维数组排序的方法。分享给大家供大家参考。具体实现方法如下:

/// <summary>
/// a generic routine to sort a two dimensional array of a specified type based on the specified column.
/// </summary>
/// <param name="array">the array to sort.</param>
/// <param name="sortcol">the index of the column to sort.</param>
/// <param name="order">specify "desc" or "descending" for a descending sort otherwise
/// leave blank or specify "asc" or "ascending".</param>
/// <remarks>the original array is sorted in place.</remarks>
/// <see cref="http://*.com/questions/232395/how-do-i-sort-a-two-dimensional-array-in-c"/>
private static void sort<t>(t[,] array, int sortcol, string order)
{
  int colcount = array.getlength(1), rowcount = array.getlength(0);
  if (sortcol >= colcount || sortcol < 0)
    throw new system.argumentoutofrangeexception("sortcol", "the column to sort on must be contained within the array bounds.");
  datatable dt = new datatable();
  // name the columns with the second dimension index values, e.g., "0", "1", etc.
  for (int col = 0; col < colcount; col++)
  {
    datacolumn dc = new datacolumn(col.tostring(), typeof(t));
    dt.columns.add(dc);
  }
  // load data into the data table:
  for (int rowindex = 0; rowindex < rowcount; rowindex++)
  {
    datarow rowdata = dt.newrow();
    for (int col = 0; col < colcount; col++)
      rowdata[col] = array[rowindex, col];
    dt.rows.add(rowdata);
  }
  // sort by using the column index = name + an optional order:
  datarow[] rows = dt.select("", sortcol.tostring() + " " + order);
  for (int row = 0; row <= rows.getupperbound(0); row++)
  {
    datarow dr = rows[row];
    for (int col = 0; col < colcount; col++)
    {
      array[row, col] = (t)dr[col];
    }
  }
  dt.dispose();
}

希望本文所述对大家的c#程序设计有所帮助。