Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
231,248 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 :)