C# C# Collections Lists Sorting Lists

I need help with IComparer implementation.

I am lost on this task. I really want to do it, but I'm not entirely sure on the steps that I need to take, logically.

Ok, so I got it working by doing

using System;
using System.Collections.Generic;

namespace Treehouse
{
    class Program
    {
        static void Main()
        {
            List<Student> students = new List<Student>
            {
                new Student() {Name = "Sally", GradeLevel = 3},
                new Student() {Name = "Bob", GradeLevel = 2},
                new Student() {Name = "Sally", GradeLevel = 2},
            };

            students.ForEach(i => Console.WriteLine("{0}\t", i.Name));

            students.Sort(new Student());

            students.ForEach(i => Console.WriteLine("{0}\t", i.Name));

        }
    }
}
using System;
using System.Collections.Generic;

namespace Treehouse
{
    class Student : IComparer<Student>
    {
        public string Name { get; set; }
        public int GradeLevel { get; set; }

        public Student()
        {

        }

        public int Compare(Student a, Student b)
        {
            int result = a.Name.CompareTo(b.Name);

            if(result == 0)
            {
                result = a.GradeLevel.CompareTo(b.GradeLevel); 
            }

            return result;
        }
    }
}

My biggest confusion is why I have to instantiate a new student object????? I don't understand how one comes to that conclusion by reading the online documentation. Any advise?

1 Answer

Daniel Medina
Daniel Medina
13,863 Points

Hello chazber,

Congratulations on solving the challenge!

I was also curious about why you'd need a new Student() too. The short answer, from what I found, is that you need to use a new Student() within your Sort() method so that you are properly implementing the IComparer interface. If you try to sort without any Student object, you'll get an InvalidOperationException.

Personally, I found this Stack Overflow post as the most helpful, particularly the answer with 207 votes:

https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object

I hope this helps!