将java翻译成c#.net
给二维数组排序
下载源代码
〖 作者:bernardvai 〗〖 大小:1k 〗〖 发布日期:2006-12-20 〗〖 浏览:0 〗
二维数组排序实例:
import java.util.*;
public class TwoDimArrayTest {
public static void main(String[] args) {
String[][] arr = {{"B","Z","K"},
{"C","X","L"},
{"A","Y","M"}} ;
//缺省(按0列升序)
Arrays.sort(arr, new TwoDimArrayComparator());
printArray(arr);
//按0列降序
Arrays.sort(arr, new TwoDimArrayComparator(0,-1));
printArray(arr);
//按1列升序
Arrays.sort(arr, new TwoDimArrayComparator(1));
printArray(arr);
//按1列降序
Arrays.sort(arr, new TwoDimArrayComparator(1,-1));
printArray(arr);
//按2列升序
Arrays.sort(arr, new TwoDimArrayComparator(2));
printArray(arr);
//按2列降序
Arrays.sort(arr, new TwoDimArrayComparator(2,-1));
printArray(arr);
}
public static void printArray(String[][] arr) {
for (int i= 0; i< arr.length ; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] +"\t");
}
System.out.println();
}
System.out.println("======================");
}
}
class TwoDimArrayComparator implements Comparator{
private int keyColumn = 0;
private int sortOrder = 1;
public TwoDimArrayComparator () {}
public TwoDimArrayComparator (int keyColumn) {
this.keyColumn = keyColumn;
}
public TwoDimArrayComparator (int keyColumn,int sortOrder) {
this.keyColumn = keyColumn;
this.sortOrder = sortOrder;
}
public int compare(Object a, Object b) {
if (a instanceof String[]) {
return sortOrder * ((String[])a)[keyColumn].compareTo(((String[])b)[keyColumn]);
} else if (a instanceof int[]){
return sortOrder * (((int[])a)[keyColumn] - ((int[])b)[keyColumn]);
} else {
return 0;
}
}
}
运行结果:
C:\java>java TwoDimArrayTest
A Y M
B Z K
C X L
======================
C X L
B Z K
A Y M
======================
C X L
A Y M
B Z K
======================
B Z K
A Y M
C X L
======================
B Z K
C X L
A Y M
======================
A Y M
C X L
B Z K
======================
------解决方案--------------------
关注