static void Main(string[] args)
{
List st = new List();
Student s1 = new Student(“za”, 1);
Student s2 = new Student(“ha”, 4);
Student s3 = new Student(“la”, 5);
Student s4 = new Student(“ka”, 3);
st.Add(s1);
st.Add(s2);
st.Add(s3);
st.Add(s4);
st.Sort();
for (int i = 0; i < st.Count; i++)
{
Console.WriteLine(st[i]);
}
//这里我们的student要实现:IComparable并添加要排序的对象
class Student:IComparable
{
string _name;
int _age;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public Student(string name,int age)
{
this._name = name;
this._age = age;
}
public override string ToString()
{
return this._name+" " +this._age;
}
public int CompareTo(Student other)
{
//根据年龄进行排序(根据姓名的首字母进行排序,若首字母相同,对下一个字母进行排序)
//if (this.Age > other.Age)
//{
// return 1;
//}
//else if (this.Age < other.Age)
//{
// return -1;
//}
//else
//{
// return 0;
//}
//根据姓名进行排序
// int result = this._name.CompareTo(other.Name);
//if (result == 0)
// {
// result = this._name.CompareTo(other.Name);
// }
// return result;
}
}

本文介绍了一个使用C#语言实现的学生对象列表排序的例子。通过继承IComparable接口,学生类可以按照姓名或年龄进行排序。代码展示了如何创建学生对象、添加到列表中,并调用Sort方法来对列表进行排序。
13万+

被折叠的 条评论
为什么被折叠?



