在linq where子句中使用方法返回值

ycggw6v2  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(462)

这里我有一个linq查询,它工作得很好,但我正在努力使它更可读。基本上,我将新的datetime范围添加到db中,但它不能与现有的范围相交。我试着写一个方法,传递开始和结束时间,并在where子句中使用返回值,但据我所知,不能在查询中使用函数。有什么建议吗?

  1. var salariesInPeriod = await db.Salaries
  2. .Where(x => x.Id != salaryIdToIgnore)
  3. .Where(x => x.UserId == userId)
  4. .Where(x =>
  5. //These filters check if there are any overlapping ends
  6. (x.StartDate <= startDate &&
  7. startDate <= (x.EndDate ?? DateTime.MaxValue))
  8. ||
  9. (x.StartDate <= (endDate ?? DateTime.MaxValue) &&
  10. (endDate ?? DateTime.MaxValue) <= (x.EndDate ?? DateTime.MaxValue))
  11. ||
  12. (startDate <= x.StartDate &&
  13. x.StartDate <= (endDate ?? DateTime.MaxValue))
  14. ||
  15. (startDate <= (x.EndDate ?? DateTime.MaxValue) &&
  16. (x.EndDate ?? DateTime.MaxValue) <= (endDate ?? DateTime.MaxValue))
  17. )
  18. .Select(x => new
  19. {
  20. x.StartDate,
  21. x.EndDate
  22. })
  23. .ToListAsync();

这就是我所尝试的:

  1. public bool CheckIntersections(DateTime currentStart, DateTime newStart, DateTime? currentEnd, DateTime? newEnd)
  2. {
  3. if ((currentStart <= newStart &&
  4. newStart <= (currentEnd ?? DateTime.MaxValue))
  5. ||
  6. (currentStart <= (newEnd ?? DateTime.MaxValue) &&
  7. (newEnd ?? DateTime.MaxValue) <= (currentEnd ?? DateTime.MaxValue))
  8. ||
  9. (newStart <= currentStart &&
  10. currentStart <= (newEnd ?? DateTime.MaxValue))
  11. ||
  12. (newStart <= (currentEnd ?? DateTime.MaxValue) &&
  13. (currentEnd ?? DateTime.MaxValue) <= (newEnd ?? DateTime.MaxValue)))
  14. {
  15. return true;
  16. }
  17. return false;
  18. }

然后我尝试在查询中使用结果:

  1. var salariesInPeriod = await db.Salaries
  2. .Where(x => x.Id != salaryIdToIgnore)
  3. .Where(x => x.UserId == userId)
  4. .Where(x => CheckIntersections(x.StartDate, startDate, x.EndDate,endDate) == true)
  5. .Select(x => new
  6. {
  7. x.StartDate,
  8. x.EndDate
  9. })
  10. .ToListAsync();

有什么办法可以简化这个问题吗?

bqujaahr

bqujaahr1#

不能在linq查询中使用任何函数。为了更好的可读性,您可以使用扩展方法:

  1. public static class SalaryQueryExtensions
  2. {
  3. public static IQueryable<Salary> WithIntersections(
  4. this IQueryable<Salary> salaries, DateTime currentStart, DateTime newStart, DateTime? currentEnd, DateTime? newEnd)
  5. {
  6. // return your query. Example:
  7. // salaries.Where(x=> x.DateTime > currentStart);
  8. }
  9. public static IQueryable<Salary> WithIgnoreId(this IQueryable<Salary> salaries, Guid id)
  10. {
  11. // return your query.
  12. }
  13. public static IQueryable<Salary> WithUserID(this IQueryable<Salary> salaries, Guid userId)
  14. {
  15. // return your query.
  16. }
  17. }

然后使用如下扩展方法:

  1. var salariesInPeriod = await db.Salaries
  2. .WithIgnoreId(salaryIdToIgnore)
  3. .WithUserId(userId)
  4. .WithIntersections(startDate,endDate)
  5. .ToListAsync();
展开查看全部

相关问题