使用Linq检查日期在范围内

编程入门 行业动态 更新时间:2024-10-28 05:20:30
本文介绍了使用Linq检查日期在范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在做一些事情,需要我检查两个日期之间的可用性.我当前的方法没有返回预期的结果.例如,说我有以下保留:

I'm currently working on something which requires me to check availability between two dates. My current methods aren't returning the expected result. For example, say I have the following reservations:

  • 2015年13月13日至2015年4月18日
  • 2015年15月15日至2015年4月20日
  • 2015年10月4日至2015年4月16日

,我希望查看所有在2015年4月15日至2015年4月16日之间的预订.从视觉上看,这看起来像:

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

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

要获取这些日期之间的所有保留,我正在使用:

To get all the reservations that fall between these dates I am using:

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); }

正在使用:

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表达式或在C#中执行此操作?理想情况下,我想将此操作作为EF查询的一部分,而不是返回所有保留,然后在此列表上执行操作.

This will only return the last two reservations though, and I believe this to be because it is checking for >= and <= on the dates, rather than checking that it falls within the range. I'm aware of using the SQL BETWEEN operator, but I was wondering if there is any way to do this using a Linq expression or from within C#? Ideally I would like to perform this as part of the EF Query as opposed to returning all reservations, then performing the operations on this list.

谢谢.

推荐答案

如果以下规则为真,则两个范围重叠:

Two ranges overlap if following rule is true:

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

通过将此规则应用于您的代码,您将得到:

By applying this rule to your code you get:

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

更多推荐

使用Linq检查日期在范围内

本文发布于:2023-10-27 22:30:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534737.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   日期   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!