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條經驗 獲得超5個贊
是否有某種原因導致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 關注
- 158 瀏覽
添加回答
舉報