I created a class Person and a HashSet. If I add the same person to the HashSet, it is not aware the Person is already present and it will add the same person multiple times. What function do I need to overwrite to have only unique elements in the HashSet?
public class Person
{
public Person(int age, string name)
{
this.age = age;
this.name = name;
}
int age;
string name;
public int Age {
get { return age; }
set { age = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public override bool Equals(object obj)
{
var other = obj as Person;
if (other == null) {
return false;
}
return age == other.age && name == other.name;
}
}
void Button1Click(object sender, EventArgs e)
{
List<Person> allPeople = new List<Person>();
Person p = new Person(15, "John");
allPeople.Add(p);
p = new Person(22, "Michael");
allPeople.Add(p);
p = new Person(16, "Alex");
allPeople.Add(p);
p = new Person(22, "Michael");
allPeople.Add(p);
p = new Person(15, "John");
allPeople.Add(p);
HashSet<Person> hashset = new HashSet<Person>();
foreach(Person pers in allPeople) {
hashset.Add(pers);
}
foreach(Person pers in hashset) {
listBox1.Items.Add(pers.Name + ", " + pers.Age);
}
}