对数组的排序
首先定义一个排序的类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
//年龄升序排列
class AgeASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.Age - y.Age;
}
}
//年龄降序排列
class AgeDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
//return y.Age - x.Age;
return y.Age.CompareTo(x.Age);
}
}
//姓名升序排列
class NameASC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.StuName.CompareTo(y.StuName);
}
}
//姓名降序排列
class NameDESC : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return y.StuName.CompareTo(x.StuName);
}
}
}
程序中以studeng.cs为对象来实现各种排序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo
{
/// <summary>
/// 带泛型接口的Student
/// </summary>
class Student : IComparable<Student>
{
public Student() { }
public Student(string name)
{
this.stuName = name;
}
public int Age { get; set; }
public int StuId { get; set; }
private string stuName;
public string StuName
{
get { return stuName; }
set { stuName = value; }
}
/// <summary>
/// 泛型接口中必须要实现的方法
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
//public int CompareTo(Student other)
//{
// //return other.StuId - this.StuId;//按照学号降序排列
// return this.StuId - other.StuId;//按照学号升序排列
//}
/// <summary>
/// 泛型接口中必须要实现的方法
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(Student other)
{
return other.StuId - this.StuId;
}
}
}
然后,在主程序中调用排序的方法:
static void Main(string[] args)
{
//实例化List<T>集合对象
List<Student> list = new List<Student>();
//添加对象元素
Student objStu1 = new Student() { Age = 20, StuId = 1001, StuName = "小张" };
Student objStu2 = new Student() { Age = 22, StuId = 1003, StuName = "小李" };
Student objStu3 = new Student() { Age = 22, StuId = 1002, StuName = "小王" };
list.Add(objStu1);
list.Add(objStu2);
list.Add(objStu3);
//默认排序
Console.WriteLine("------------默认排序------------");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("姓名:{0} 年龄:{1} 学号:{2}", list[i].StuName, list[i].Age, list[i].StuId);
}
//年龄降序排序
Console.WriteLine("------------年龄降序排序------------");
list.Sort(new AgeDESC());
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("姓名:{0} 年龄:{1} 学号:{2}", list[i].StuName, list[i].Age, list[i].StuId);
}
//姓名升排序
Console.WriteLine("------------姓名升序排序------------");
list.Sort(new NameASC());
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("姓名:{0} 年龄:{1} 学号:{2}", list[i].StuName, list[i].Age, list[i].StuId);
}
Console.ReadLine();
}