IComparer接口示例代码

定义学生类

public class Student
{
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Age { get; set; }
}

自定义比较器AgeComparer实现接口IComparer<Student>对学生年龄进行比较。

public class AgeComparer:IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        return x.Age.CompareTo(y.Age);
    }
}

自定义比较器NameComparer实现接口IComparer<Student>对学生姓名进行比较。

public class NameComparer:IComparer<Student>
{
    public int Compare(Student x, Student y)
    {
        return x.Name.CompareTo(y.Name);
    }
}

调用List<T>.Sort方法实现stuList按照学生的年龄与姓名排序。

static void Main(string[] args)
{
    List<Student> stuList = new List<Student>();
    stuList.Add(new Student() { Name = "aki", Sex = "Man", Age = 18 });
    stuList.Add(new Student() { Name = "cki", Sex = "Woman", Age = 20 });
    stuList.Add(new Student() { Name = "dki", Sex = "Woman", Age = 16 });
    stuList.Add(new Student() { Name = "bki", Sex = "Man", Age = 21 });
    stuList.Add(new Student() { Name = "fki", Sex = "Woman", Age = 19 });
    stuList.Sort(new AgeComparer());
    Console.WriteLine("按照年龄排序:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);
    }
    stuList.Sort(new NameComparer()); 
    Console.WriteLine();
    Console.WriteLine("按照名称排序:");
    foreach (Student stu in stuList)
    {
        Console.WriteLine("Name=" + stu.Name + ";Sex=" + stu.Sex + ";Age=" + stu.Age);
    }
}

代码执行结果如下。

IComparer接口示例代码_第1张图片

 

你可能感兴趣的:(接口,sort,IComparer,IComparerT,ListT)