示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TSortTest
{
class Program
{
static void Main(string[] args)
{
List<Foo> foos = new List<Foo>();
Random random = new Random();
for (int i = 0; i < 10; i++)
{
Foo foo = new Foo();
foo.score = random.Next(0, 100);
foos.Add(foo);
}
Console.WriteLine("排序前:");
foreach (var foo in foos)
{
Console.Write(foo.score + " ");
}
IComparer<Foo> f = new Foo();
foos.Sort(f.Compare);
Console.WriteLine("\n排序后:");
foreach (var foo in foos)
{
Console.Write(foo.score+" ");
}
Console.Read();
}
}
public class Foo : IComparer<Foo>
{
public int score;
public int Compare(Foo a, Foo b)
{
if (a.score > b.score)
return 1;
else if (a.score < b.score)
return -1;
return 0;
}
}
}
运行测试