This question already has answers here:
List.Except is not working
(2 个回答)
4年前关闭。
我有一些方法可以返回过去 360 天、180 天和 90 天未查询的联系人列表。
过去 361 天没有被查询的一个人,也会被 180 天和 90 天的查询返回。
我以为我可以用一个异常(exception)来做到这一点,但这肯定行不通,
GetOldContacts 方法
而我的逻辑除外
问题是第二个查询将第一个查询返回给我,它不应该 What's the best strategy for Equals and GetHashCode? What is the best algorithm for an overridden System.Object.GetHashCode?
要指定内联比较器,请查看:
Can I specify my explicit type comparator inline?
(2 个回答)
4年前关闭。
我有一些方法可以返回过去 360 天、180 天和 90 天未查询的联系人列表。
过去 361 天没有被查询的一个人,也会被 180 天和 90 天的查询返回。
我以为我可以用一个异常(exception)来做到这一点,但这肯定行不通,
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);
问题是第二个查询将第一个查询返回给我,它不应该
最佳答案
Linq 的 Except
通过 Equals()
比较对象。您需要覆盖 Contacto
的 Equals
和 GetHashCode
。
之前的许多问题解释了如何:
Except
也有一个重载,如果你更喜欢实现一个 IEqualityComparer
而不是覆盖函数要指定内联比较器,请查看:
关于c# - LINQ 除了没有按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43809967/
10-12 20:30