C# C# Collections Sets and Dictionaries Hashing

Feeding HashSet constructor a List with duplicate item not automatically removing it.

using System;
using System.Collections.Generic;

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

            HashSet<Student> students = new HashSet<Student>(pre);
            SchoolRoll schoolRoll = new SchoolRoll();
            schoolRoll.AddStudents(students);

            foreach(Student student in schoolRoll.Students)
            {
                Console.WriteLine($"{student.Name} is in grade {student.GradeLevel}");
            }
        }
    }
}

Anybody know why?

2 Answers

Steven Parker
Steven Parker
186,980 Points

A new instance of a HashSet<T> class uses the default equality comparer for the set type. The definition of "Student" is not shown here, but my first guess would be that it needs a comparer that will judge equality using the contents.

Thanks Steve. I should've just waited to watch the next vids :)