LINQ - somewhat depending on conditions

I want to query a table with some conditions based on user input.

I have this code:

   IQueryable<Turno> turnoQuery = dc.Turno;

    if (helper.FechaUltimaCitaDesde != DateTime.MinValue)
    {
        turnoQuery = turnoQuery.Where(t => t.TurnoFecha >= helper.FechaUltimaCitaDesde);
    }
    if (helper.FechaUltimaCitaHasta != DateTime.MinValue)
    {
       turnoQuery = turnoQuery.Where(t => t.TurnoFecha <= helper.FechaUltimaCitaHasta);
    }

    if (helper.SoloCitasConsumidas)
    {
       turnoQuery = turnoQuery.Where(t => t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido));
    }
    else if(helper.AnuladoresDeCitas)
    {
     turnoQuery = turnoQuery.Where(t => t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente));
    }

The problem I am facing is that the where clause is overwritten last.

What is the correct way to do something like this in LINQ?

The helper object is a user class that stores user input dates for this example.

+3
source share
1 answer

You can combine expressions using a series of triple operations. This has not been verified, so there may be some syntax issues, but here's the basic idea:

turnoQuery = turnoQuery.Where(
  t => t.TurnoFecha >= helper.FechaUltimaCitaDesde != DateTime.MinValue ? helper.FechaUltimaCitaDesde : DateTime.MinValue &&
       t.TurnoFecha <= helper.FechaUltimaCitaHasta != DateTime.MinValue ? helper.FechaUltimaCitaHasta : DateTime.MaxValue &&
       helper.SoloCitasConsumidas ? t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido : 
           t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente) &&
       helper.FechaUltimaCitaDesde != DateTime.MinValue ? t.TurnoFecha >= helper.FechaUltimaCitaDesde : t.TurnoFecha <= helper.FechaUltimaCitaHasta &&
       helper.SoloCitasConsumidas ? t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido) : t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente)
);
+1
source

Source: https://habr.com/ru/post/1746425/


All Articles