0

I'm trying to remove duplicate values ​​from a list, but it's not working. I click the button to execute the distinct function, but the final result and the same input

List<Cliente> clientes = new List<Cliente>();

Cliente.cs

namespace cadastroClientes
{
    public class Cliente
    {
        public int ID { get; set; }
        public string Nome { get; set; }
        public string Email { get; set; }
        public bool Enviado { get; set; }

        public Cliente(int id, string nome, string email, bool enviado = false)
        {
            ID = id;
            Nome = nome;
            Email = email;
            Enviado = enviado;
        }

        public override string ToString()
        {
            return string.Format("{0}", Nome);
        }
    }
}

Remove Duplicated:

List<Cliente> distic = clientes.Distinct().ToList();
StringBuilder sb = new StringBuilder();
foreach (Cliente cliente in distic)
{
   sb.AppendLine(cliente.Nome);
}

MessageBox.Show(sb.ToString());
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sharp Always
  • 61
  • 2
  • 6

1 Answers1

1

If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the IEquatable generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide GetHashCode and Equals methods.

https://msdn.microsoft.com/en-us/library/bb348436(v=vs.110).aspx

Bruno Avelar
  • 670
  • 4
  • 16