Search code examples
c#listobjectpointers

Swapping between 2 objects in a list c#


I’m trying to sort an array of Student objects alphabetically by name and swap two objects in the list. However, after swapping, I’m noticing that the objects sometimes appear to become identical, and I'm not sure how to prevent this from happening.

for(int i = 0; i < this.lastPosition; i++)
        {
            if(this.list[i].GetName().CompareTo(this.list[i+1].GetName()) > 0) {
                Student temp = this.list[i];
                this.list[i] = this.list[i+1];
                this.list[i+1] = temp;
            }
        }

Before the sorting:

Rina 034377281 Parent: Rozz 044377281
Bina 034377281 Parent: Rozz 044377281
Cina 034377281 Parent: Noa 050569126

After the sorting:

Bina 034377281 Parent: Rozz 044377281
Cina 034377281 Parent: Noa 050569126
Cina 034377281 Parent: Noa 050569126

This is the object StudentList:

public class StudentList
{
    public const int MaxStudent = 38;
    private Student[] list;
    private int lastPosition;

And there is Student:

public class Student
{
    private string name;
    private string phoneNum;
    Parent parent;

I would appreciate your help.


Solution

  • Your code seems mostly correct, but I think you might encounter an Index out of Bounds error, because you are comparing (list[i]) with the next element (list[i+1]). This means when i reaches the second-to-last element (i = lastPosition - 1), you’ll be trying to access list[i+1], which is out of bounds.