C#实现对二维数组排序的方法
作者:红薯 时间:2023-06-19 09:09:08
本文实例讲述了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://stackoverflow.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#程序设计有所帮助。
标签:C#,数组,排序
0
投稿
猜你喜欢
Android Fragment的用法实例详解
2022-01-21 03:39:40
Spring 注入static属性值方式
2022-07-21 12:40:18
动态webservice调用接口并读取解析返回结果
2021-10-19 07:05:45
浅析C#中StringBuilder类的高效及与String的对比
2022-09-14 15:54:04
Android用户注册界面简单设计
2023-07-13 02:59:50
Android对话框AlertDialog详解
2023-06-20 01:47:19
Android运动健康睡眠自定义控件的实现
2021-07-17 22:52:35
Spring深入探索AOP切面编程
2023-05-27 09:37:16
break在scala和java中的区别解析
2021-08-02 19:24:46
SpringBoot配置文件中密码属性加密的实现
2022-07-08 18:32:03
Java数据结构及算法实例:三角数字
2023-08-24 17:52:25
Java全面分析面向对象之继承
2023-11-23 11:55:59
C#实现简单的天气预报示例代码
2022-03-22 22:52:59
一款域名监控小工具 Domain(IP)Watcher 实现代码
2023-09-15 11:55:44
在Android中使用WebSocket实现消息通信的方法详解
2022-06-10 06:26:18
深入理解C# 装箱和拆箱(整理篇)
2023-10-04 02:13:13
SpringBoot中的PUT和Delete请求使用
2022-01-22 19:33:32
Java Swing JProgressBar进度条的实现示例
2023-07-15 17:48:47
基于Java生成GUID的实现方法
2022-04-09 02:44:09
Android开发之SQLite的使用方法
2022-11-12 05:26:38