Make a list without duplicates in C#

[list without duplicates]

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 Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.

This entry was posted in generic, lists and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *