2017-05-05 28 views
1

我有一些方法可以返回我最近360天,180天和90天內未查詢的聯繫人列表。LINQ除非沒有按預期的方式工作

在過去的361天內沒有被查詢的一個人也將在180天和90天的查詢中返回。

我想我能做到這一點與除,但是那肯定不是工作,

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方法

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; 
    } 

} 

而我除了邏輯

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

的問題是第二個查詢是返回第一個項目,它不應該

回答

4

Linq的Except比較對象的Equals()。您需要覆蓋ContactoEqualsGetHashCode

以前的許多問題,講解如何:

Except也有,如果你喜歡重寫功能,以實現一個而不是臨危的IEqualityComparer超負荷

用於指定比較器內聯外觀:

+0

任何更簡單的方法? –

+0

@ LuisValencia-MVP - 查看更新 –