【问题标题】:LINQ Except not working as expected [duplicate]LINQ除了没有按预期工作[重复]
【发布时间】:2017-05-05 16:40:13
【问题描述】:

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

最近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);

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

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc linq


    【解决方案1】:

    Linq 的Except 通过Equals() 比较对象。您需要覆盖ContactoEqualsGetHashCode

    许多以前的问题解释了如何:

    Except 也有一个重载,如果您更喜欢实现一个而不是覆盖函数,它会接收一个 IEqualityComparer

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

    【讨论】:

    • 有更简单的方法吗?
    猜你喜欢
    • 2023-04-05
    • 2014-12-17
    • 2012-11-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2013-03-25
    • 2021-01-16
    相关资源
    最近更新 更多