Check dates fall into range using Linq

I'm currently working on what requires checking for two dates. My current methods do not return the expected result. For example, let's say I have the following reservations:

  • 04/13/2015 to 04/18/2015
  • 04/15/2015 to 04/20/2015
  • 04/10/2015 to 04/16/2015

and I want to see all reservations that are between 04/15/2015 to 04/16/2015. Visually, it might look like this:

              15    16
      X________|_____|______X
               |X____|_____________X
X______________|____X|
               |     | 

To get all reservations that relate to these dates, I use:

public List<ReservationClientModel> GetReservationsByDateRange(int id, DateTime checkin, DateTime checkout)
    {
        var reservation = _repository.FindAllBy(x => 
            (x.StartDate >= checkin && x.EndDate <= checkout) ||
            (x.StartDate >= checkin && x.StartDate <= checkout) ||
            (x.EndDate >= checkin && x.EndDate <= checkout)),
            y => y.RoomTypeNav)
            .ToList();

        return Mapper.Map<List<ReservationClientModel>>(reservation);
    }

Uses:

public IEnumerable<TEntity> FindAllBy(Expression<Func<TEntity, bool>> predicate, params Expression<Func<TEntity, object>>[] includes)
    {
        var set = _dbSet.AsQueryable();
        set = includes.Aggregate(set, (current, include) => current.Include(include));
        return set.Where(predicate);
    }

, , , >= <= , , . SQL BETWEEN, , Linq #? EF, , .

.

+4
1

, :

(StartDate1 <= EndDate2) and (EndDate1 >= StartDate2)

, :

var reservation = _repository
    .FindAllBy(x => x.StartDate <= checkout && x.EndDate >= checkin,  
               y => y.RoomTypeNav)
    .ToList();
+8

All Articles