[英]Use method return value inside linq where clause
在这里,我有一个 linq 查询,它工作正常,但我试图让它更具可读性。 基本上,我将新的 DateTime 范围添加到数据库中,但它不能与现有的相交。 我尝试编写一个方法,传递开始和结束时间并在 where 子句中使用返回值,但据我了解,不能在查询中使用 function。 对此有何建议?
var salariesInPeriod = await db.Salaries
.Where(x => x.Id != salaryIdToIgnore)
.Where(x => x.UserId == userId)
.Where(x =>
//These filters check if there are any overlapping ends
(x.StartDate <= startDate &&
startDate <= (x.EndDate ?? DateTime.MaxValue))
||
(x.StartDate <= (endDate ?? DateTime.MaxValue) &&
(endDate ?? DateTime.MaxValue) <= (x.EndDate ?? DateTime.MaxValue))
||
(startDate <= x.StartDate &&
x.StartDate <= (endDate ?? DateTime.MaxValue))
||
(startDate <= (x.EndDate ?? DateTime.MaxValue) &&
(x.EndDate ?? DateTime.MaxValue) <= (endDate ?? DateTime.MaxValue))
)
.Select(x => new
{
x.StartDate,
x.EndDate
})
.ToListAsync();
这就是我尝试过的:
public bool CheckIntersections(DateTime currentStart, DateTime newStart, DateTime? currentEnd, DateTime? newEnd)
{
if ((currentStart <= newStart &&
newStart <= (currentEnd ?? DateTime.MaxValue))
||
(currentStart <= (newEnd ?? DateTime.MaxValue) &&
(newEnd ?? DateTime.MaxValue) <= (currentEnd ?? DateTime.MaxValue))
||
(newStart <= currentStart &&
currentStart <= (newEnd ?? DateTime.MaxValue))
||
(newStart <= (currentEnd ?? DateTime.MaxValue) &&
(currentEnd ?? DateTime.MaxValue) <= (newEnd ?? DateTime.MaxValue)))
{
return true;
}
return false;
}
然后我尝试在查询中使用结果:
var salariesInPeriod = await db.Salaries
.Where(x => x.Id != salaryIdToIgnore)
.Where(x => x.UserId == userId)
.Where(x => CheckIntersections(x.StartDate, startDate, x.EndDate,endDate) == true)
.Select(x => new
{
x.StartDate,
x.EndDate
})
.ToListAsync();
任何想法如何简化该查询?
您不能在 linq 查询中使用任何 function。 为了更好的可读性,您可以使用扩展方法:
public static class SalaryQueryExtensions
{
public static IQueryable<Salary> WithIntersections(
this IQueryable<Salary> salaries, DateTime currentStart, DateTime newStart, DateTime? currentEnd, DateTime? newEnd)
{
// return your query. Example:
// salaries.Where(x=> x.DateTime > currentStart);
}
public static IQueryable<Salary> WithIgnoreId(this IQueryable<Salary> salaries, Guid id)
{
// return your query.
}
public static IQueryable<Salary> WithUserID(this IQueryable<Salary> salaries, Guid userId)
{
// return your query.
}
}
然后使用这样的扩展方法:
var salariesInPeriod = await db.Salaries
.WithIgnoreId(salaryIdToIgnore)
.WithUserId(userId)
.WithIntersections(startDate,endDate)
.ToListAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.