class Program
{
static void Main(string[] args)
{
TestClass t1 = new TestClass();
t1.Score = 90;
t1.Name = "lucy";
TestClass t2 = new TestClass();
t2.Score = 100;
t2.Name = "lili";
List<TestClass> mylist = new List<TestClass>();
mylist.Add(t1);
mylist.Add(t2);
mylist.Sort(new CompareName());
//mylist.Sort();
for (int i = 0; i < mylist.Count; i++)
{
Console.WriteLine(mylist[i].Name);
Console.WriteLine(mylist[i].Score);
}
Console.Read();
}
}
class TestClass : IComparable<TestClass>
{
public int Score = 0;
public string Name = string.Empty;
public int CompareTo(TestClass other)
{
if (Score > other.Score)
{
return 1;
}
else if (Score == other.Score)
{
return 0;
}
else
{
return -1;
}
}
}
class CompareName :IComparer<TestClass>
{
//比较器
public int Compare(TestClass x, TestClass y)
{
return x.Name.CompareTo(y.Name);
}
}
用泛型的比较接口和比较器接口。
比较接口 IComparable <>,比较器类接口: IComparer<>
sort() ;//比较接口排序
sor(比较器);//比较类排序 |