Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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();

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

Anybody know why?

2 Answers

Steven Parker
Steven Parker
221,325 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 :)