排序是经常要用到的功能,遇到排序问题,第一感觉就是自己写排序算法,其实还可以用.Net类库实现排序功能。
如:SortedList,Array等,他们都能根据ICompare接口或者IComparable接口实现排序,像一些常用类型如:string,int都实现了IComparable接口。string 还有.net提供的ICompare的实现StringComparer类,此类提供了许多排序方式。
下面的例子用Array实现排序,虽然只是一个Int数组,但是其他复杂类型都可以用相同方法处理
public
void
Sort()
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
int[,] i = new int[2, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 } };
int[] b = new int[6];
for (int j = 0; j < i.GetLength(0); j++)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
for (int k = 0; k < i.GetLength(1); k++)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int l = i.GetLength(1);
b[j * l + k] = i[j, k];
}
}
ReverserSort ms = new ReverserSort();
Array.Sort(b,ms);
}
}
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
public
class
ReverserSort:IComparer
<
int
>
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
int IComparer<int>.Compare(int x, int y)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return -(x - y);
}
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
Sort()实现了由大到小的排序。排序的顺序通过IComparer接口规定。如果把返回值的“-”去掉,则按照由小到大的顺序。
实现ICompare接口是最灵活的排序实现。如果只是Int数组的排序,通过Array的Sort(),Reverse就可以了,Sort的无参重载会自动调用int的IComparable实现