首先:新建一个类,继承于IComparer<T>,其中T为任意类型
然后:实现public int Compare( T x, T y )方法,x>y返回大于0的值,小于返回小于0的值,等于返回0。
最后,使用Sort<T>( T[] array, IComparer<T> comparer )方法即可。
提示:默认是升序,如果要降序,完了之后再来一次Array.Reverse( )即可。
示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace templeUse {
class Program {
static void Main( string[] args ) {
Program p = new Program();
p.Run();
}
public void Run() {
Rank r1 = new Rank();
r1.age = 20;
r1.money = 10000;
Rank r2 = new Rank();
r2.age = 10;
r2.money = 20000;
Rank r3 = new Rank();
r3.age = 20;
r3.money = 20000;
Rank r4 = new Rank();
r4.age = 20;
r4.money = 10000;
Rank[] ary = new Rank[4];
ary[0] = r1;
ary[1] = r2;
ary[2] = r3;
ary[3] = r4;
Array.Sort<Rank>( ary, new sort() );
foreach ( var item in ary ) {
Console.WriteLine( "age:{0},money{1}", item.age,item.money);
}
Console.ReadKey();
Array.Reverse( ary );
foreach ( var item in ary ) {
Console.WriteLine( "age:{0},money{1}", item.age, item.money );
}
Console.ReadKey();
}
}
}
class Rank{
public int age;
public int money;
}
class sort : IComparer<Rank> {
public int Compare( Rank x, Rank y ) {
if ( x.age > y.age )
return 1;
if ( x.age == y.age ) {
if ( x.money > y.money )
return 1;
else if ( x.money == y.money )
return 0;
else
return -1;
}
return -1;
}
}