14.对象的动态排序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _4.对象的动态排序
{
class Program
{
static void Main(string[] args)
{
//创建一组对象
Student stu1 = new Student() { StudentId = 1001, StudentName = "小李", Age = 20 };
Student stu2 = new Student() { StudentId = 1008, StudentName = "张红", Age = 27 };
Student stu3 = new Student() { StudentId = 1006, StudentName = "汪洋", Age = 22 };
Student stu4 = new Student() { StudentId = 1002, StudentName = "郝欣", Age = 28 };
//将对象添加到集合
List<Student> list = new List<Student>() { stu1, stu2, stu3, stu4 };
//排序
list.Sort(new StudNameASC());//学生姓名升序排序
//输出排序结果
foreach (Student item in list)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
}
Console.WriteLine("----------------学生姓名升序排序后反转------------------");
list.Reverse();//学生姓名升序排序后反转
//输出排序结果
foreach (Student item in list)
{
Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
}
Console.ReadKey();
}
}
#region 排序类
class Student
{
public Student()
{
}
public Student(int stuId, string stuNmae)
{
this.StudentId = stuId;
this.StudentName = stuNmae;
}
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
#region 具体的排序类
////////添加默认排序类,分别实现排序比较器接口:IComparer<>
//你需要几种排序方法就加几个排序类
/// <summary>
/// 学生姓名的升序
/// </summary>
class StudNameASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
// throw new NotImplementedException();
return x.StudentName.CompareTo(y.StudentName);//升序
}
}
/// <summary>
/// 学生姓名的降序
/// </summary>
class StudNameDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
//throw new NotImplementedException();
return y.StudentName.CompareTo(x.StudentName);
}
}
/// <summary>
/// 学生年龄的升序
/// </summary>
class AgeASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
//throw new NotImplementedException();
return x.Age.CompareTo(y.Age);
}
}
/// <summary>
///学生年龄的降序
/// </summary>
class AgeDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
// throw new NotImplementedException();
return y.Age.CompareTo(x.Age);
}
}
#endregion
#endregion
}