Aheho Aheho - 2 months ago 7
C# Question

Using Custom IComparer to Order by Pointer value

I have a class that defines a student, and has a property (FollowedBy) that is immediately behind that student. I am looking for a way to order the students based on this linkage.

class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public int? FollowedBy { get; set; }
}

var lstStudents = new List<Student>()
{ new Student() { StudentID = 2, Name = "Mark", FollowedBy =4 },
new Student() { StudentID = 1, Name = "Sam", FollowedBy = 2},
new Student() { StudentID = 4, Name = "Fred", FollowedBy =null } ,
new Student() { StudentID = 3, Name = "Janice", FollowedBy = 1}};

for (var s in lstStudents.OrderBy(x => ????))
{
console.Write(s.Name);
}

// The output I'm looking for
// Janice
// Sam
// Mark
// Fred

Answer
    public List<Student> GetOrderedStudents(List<Student> students)
    {
        Student[] reverseOrder = new Student[students.Count];

        Student last = students.Single(s => s.FollowedBy == null);

        reverseOrder[0] = last;
        Student next = last;

        for (var i = 1; i < students.Count; i++)
        {
            next = students.Single(s => s.FollowedBy == next.StudentID);
            reverseOrder[i] = next;
        }

        return reverseOrder.Reverse().ToList();  
    }