Title: Make a list without duplicates in C#
This example builds a list of Person objects without duplicates. The following code shows the Person class.
public class Person : IEquatable<Person>
{
public string FirstName, LastName;
public Person(string first_name, string last_name)
{
FirstName = first_name;
LastName = last_name;
}
public override string ToString()
{
return FirstName + " " + LastName;
}
public bool Equals(Person other)
{
if (other == null) return false;
if (FirstName != other.FirstName) return false;
if (LastName != other.LastName) return false;
return true;
}
}
This class declares simple FirstName and LastName fields, defines an initializing constructor, and overrides the class's ToString method.
It also implements the IEquatable interface. That interface requires the Equals method, which in this example returns true if two Person objects represent the same person.
The following code shows how the program uses the class.
private List<Person> People = new List<Person>();
// Add a new Person if that Person isn't already in the list.
private void btnAdd_Click(object sender, EventArgs e)
{
lstPeople.DataSource = null;
Person person =
new Person(txtFirstName.Text, txtLastName.Text);
if (!People.Contains(person))
People.Add(person);
txtFirstName.Clear();
txtLastName.Clear();
txtFirstName.Focus();
lstPeople.DataSource = People;
}
The code starts by declaring the People list.
If you enter a first and last name and click the Add button, the Click event handler executes. It sets the ListBox control's DataSource property to null so it no longer displays any previous values. The event handler then uses the values you entered to create a new Person object.
Next the code uses the list's Contains method to see if it already contains an object with the same first and last names. The Person class implements IEquatable so the Contains method uses it to see if the list already contains an object that is equivalent to the new one. If Contains returns false, the code adds the new item to the list.
The event handler then clears the TextBox controls to get ready for the next name. It finishes by setting the ListBox control's DataSource property to the People list so it displays the objects in the list.
Download the example to experiment with it and to see additional details.
|