最近在听陈广老师的C#视频。把视频中相应的代码整理出来,方便以后用的时候查找
/*
* 由SharpDevelop创建。
* 用户: Administrator
* 日期: 2012-3-14
* 时间: 14:39
*
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
*/
using System;
using System.Collections.Generic;
class Student:IComparable<Student>
{
private string _name; //姓名
private int _age; //年龄
private int _Number; //学号
public Student(){}
public Student(string name,int age,int num)
{
this._name = name;
this._age = age;
this._Number = num;
}
/// <summary>
/// 实现IComparable接口中的默认排序的方法
/// 这里是按姓名排序
/// </summary>
/// <param name="right"></param>
/// <returns></returns>
public int CompareTo(Student right)
{
return _name.CompareTo(right._name);
}
public override string ToString()
{
return string.Format("[Student Name={0}, Age={1}],Number={2}", _name, _age,_Number);
}
#region 实现按年龄排序
private static AgeComparer _AgeCom;
public static IComparer<Student> AgeCom
{
get
{
//保证_AgeCom在使用时只实例化一次,不使用时不实例化
if(_AgeCom==null)
{
_AgeCom = new AgeComparer();
}
return _AgeCom;
}
}
private class AgeComparer:IComparer<Student>
{
/// <summary>
/// 实习IComparer接口的中方法
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public int Compare(Student left,Student right)
{
return left._age.CompareTo(right._age);
}
}
#endregion
#region 实现按年龄排序
private static NumComparer _NumCom;
public static IComparer<Student> NumCom
{
get
{
//保证_NumCom在使用时只实例化一次,不使用时不实例化
if(_NumCom==null)
{
_NumCom = new NumComparer();
}
return _NumCom;
}
}
private class NumComparer:IComparer<Student>
{
/// <summary>
/// 实习IComparer接口的中方法
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public int Compare(Student left,Student right)
{
return left._Number.CompareTo(right._Number);
}
}
#endregion
}
class Test
{
static void Main()
{
Student[] stu = new Student[5];
stu[0]=new Student("张三",22,104);
stu[1]=new Student("李四",32,101);
stu[2]=new Student("王五",42,103);
stu[3]=new Student("马六",52,102);
stu[4]=new Student("钱七",12,100);
//默认字段排序
Array.Sort(stu);
foreach(Student s in stu)
{
Console.WriteLine(s);
}
Console.WriteLine();
//按指定的字段排序(这里按年龄)
Array.Sort(stu,Student.AgeCom);
foreach(Student s in stu)
{
Console.WriteLine(s);
}
Console.WriteLine();
//按指定的字段排序(这里按学号)
Array.Sort(stu,Student.NumCom);
foreach(Student s in stu)
{
Console.WriteLine(s);
}
}
}