LINQ除非按预期工作

我有一些方法可以返回我在过去360天,180天和90天内未查询过的联系人列表。

在过去361天内未被查询的一个人也将在180天和90天的查询中返回。

我以为我可以用Except做到这一点,但那肯定不行,

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 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>().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 contactosDoceMeses = GetOldContacts(ConfigurationSettings.Ciclo3Dias); IEnumerable contactosSeisMeses = GetOldContacts(ConfigurationSettings.Ciclo2Dias).Except(contactosDoceMeses); IEnumerable contactosTresMeses = GetOldContacts(ConfigurationSettings.Ciclo1Dias).Except(contactosSeisMeses); 

问题是第二个查询返回第一个项目,它不应该

Linq的ExceptEquals()比较对象。 你需要覆盖ContactoEqualsGetHashCode

以前的许多问题都解释了

  • Equals和GetHashCode的最佳策略是什么?
  • 覆盖System.Object.GetHashCode的最佳算法是什么?

Except还有一个重载接收IEqualityComparer如果你更喜欢实现一个而不是覆盖函数

要指定比较器内联,请查看:

  • 我可以指定内联的显式类型比较器吗?