2 回答
TA贡献1806条经验 获得超5个赞
正如一些评论员指出的那样,您可能需要访问Student和比较它们的属性,然后交换对象。
所以像这样:
public static void SortStudents(IList<Student> students)
{
//We change this to Type Student, not string.
Student temp;
for (int i = 0; i < students.Count; i++)
{
for (int j = 0; j < students.Count; j++)
{
//We look at the Properties of the object, not the Object.ToString()
if (string.Compare(students[i].FirstName, students[j].FirstName) < 0)
{
//Here we are swapping the objects, because we have determined
//Their first names aren't in alphabetical order.
temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
//For loop, or Foreach loop here to iterate through your collection (ILIST)
}
TA贡献1821条经验 获得超4个赞
是否有某种原因导致Student该类无法通过实现IComparable接口来实现这种“排序”逻辑?使用 aList<Student>来保存Student对象将使用此CompareTo方法对对象进行“排序”。这将允许类以任何你想要的方式“排序”。在这种情况下,它按姓氏然后按名字排序。你试过这样做吗?它可能看起来像下面...
public class Student : IComparable {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string StudentNumber { get; set; }
public string Gender { get; set; }
public string FieldOfStudy { get; set; }
public int CompareTo(object obj) {
Student that = (Student)obj;
if (this.LastName.Equals(that.LastName))
return this.FirstName.CompareTo(that.FirstName);
return this.LastName.CompareTo(that.LastName);
}
}
然后,“排序” aList<Student>将只是......
Students.Sort();
- 2 回答
- 0 关注
- 108 浏览
添加回答
举报