检查一个日期是否落在日期范围之间-Linq 查询

Check One Date is falling Between Date Range-Linq query

我正在 database.From 中存储员工的休假信息,并且 To Date 将存储在 DB.I 想要阻止员工申请休假,当它进入已申请的休假范围时。

例如:假设一名员工已在 01/01/2015 至 05/01/2015 之间申请休假,

i)if user again try to apply leave for 04/01/2015 to 07/01/2015,then i  need to block that one.
ii)if user again try to apply leave for 05/01/2015 to 05/01/2015,then i  need to block that one.

我如何使用 Linq 查询找到它

你可以试试下面的方法

    return (from t1 in db.Employee where ( empid == t1.EmplyeeId &&
date1 >= t1.LeaveStart && date2 <= t1.LeaveEnd))

你可以试试下面的方法,答案很详细

int cntleaves = (from values in dbcontext.User_master
                       where values.iUser_id == Userid &&
                               ((values.dtStart_date >= Startdate &&
                                values.dtEnd_date <= Enddate)
                                 ||
                                 (values.dtStart_date <= Startdate &&
                                values.dtEnd_date <= Enddate))
                       select values).ToList().Count();

        if (cntleaves > 0) {
            ViewBag.Message = "You have already applied for leaves !";            
        }

试试这个:

var startDate = new DateTime(2015, 01, 04);
var endDate = new DateTime(2015, 01, 07);
if (_context.AppliedLeaves.Any(x => 
     x.UserId == userId &&
     ((startDate >= x.StartDate && startDate <= x.EndDate) || 
      (endDate >= x.StartDate && endDate <= x.EndDate)))
{
    throw Exception("You cannot apply this period");
}
IF EXISTS (
SELECT * FROM table WHERE user = @user AND (
@newStartDate BETWEEN appliedStartDate AND appliedEndDate

)
PRINT 'Can not apply'
ELSE PRINT 'Can apply'

另一种更好的方法是为 DateTime class 创建一个扩展方法:

public static bool Between(this DateTime input, DateTime date1, DateTime date2)
{
    return (input > date1 && input < date2);
}

然后您可以将其与 linq 谓词 where 子句一起使用。

if ( leaves.Where( l => l.empId == empId && dateApplied.Between(l.from, l.to)).Any()) { ... error... }

PS: 这只是你方向的伪代码。

此post与范围内两列之间的查询有关,可能对某些开发人员有所帮助。

第一步:进入列表

var Price = GetLoad().ToList();

第二步:您的搜索项

字符串代码="PLUS";

var Total_Squares = 101: //值需要在整数范围内检查

DateTime Checkdate = Convert.ToDateTime("2012-10-03"); //值需要在日期

内检查

查询 1 以检查整数范围以及字符串值

var filteredCodeWithSquare = Price.Where(C => C.Code.StartsWith(code))

.FirstOrDefault(r => r.FromSquare <= Total_Squares && r.ToSquare >= Total_Squares); 一种 Query2 检查日期范围

var daterange = Price.FirstOrDefault(d => d.FromIntall

<= 检查日期 && d.ToInstall >= 检查日期);