3

I have some methods which return me a list of contacts that have not been queried on the last 360 days, 180 days and 90 days.

One person that has not been queried on the last 361 days, will also be returned by the query of 180 days and 90 days.

I thought I could do that with an Except, but thats certainly not working,

public class Contacto
{
    public int IdContacto { get; set; }
    public string PrimerApellido { get; set; }
    public string PrimerNombre { get; set; }
    public string SegundoApellido { get; set; }
    public string SegundoNombre { get; set; }
    public object Telefonos { get; set; }
    public int TipoTelefono { get; set; }
    public int IdEstado { get; set; }
    public DateTime? FechaArchivado { get; set; }
    public DateTime? FechaConsulta { get; set; }

GetOldContacts method

private static List<Contacto> GetOldContacts(int numberOfDays)
{
    try
    {
        DateTime filter = DateTime.Now.AddDays(-numberOfDays);
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(ConfigurationSettings.Apiurl);
        HttpResponseMessage response = client.GetAsync("api/ContactosDepurar?FechaInicial="+filter.ToShortDateString()).Result;
        if (response.IsSuccessStatusCode)
        {
            return response.Content.ReadAsAsync<List<Contacto>>().Result;
        }
        else
        {
            System.Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            return null;
        }
    }
    catch (Exception ex)
    {
        System.Console.WriteLine(ex.Message);
        return null;
    }

}

And my Except logic

IEnumerable<Contacto> contactosDoceMeses = GetOldContacts(ConfigurationSettings.Ciclo3Dias);
IEnumerable<Contacto> contactosSeisMeses = GetOldContacts(ConfigurationSettings.Ciclo2Dias).Except<Contacto>(contactosDoceMeses);
IEnumerable<Contacto> contactosTresMeses = GetOldContacts(ConfigurationSettings.Ciclo1Dias).Except<Contacto>(contactosSeisMeses);

The problem is the second query is returning me the items on the first and it shouldnt

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Luis Valencia
  • 32,619
  • 93
  • 286
  • 506

1 Answers1

4

Linq's Except compares objects by their Equals(). You need to override Contacto's Equals and GetHashCode.

Many previous questions explain how:

Except also has an overload that recieves an IEqualityComparer if you prefer to implement one instead of overriding the functions

For specifying a comparer inline look at:

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95