添加额外的linq where子句基于变量

时间:2014-05-29 09:00:03

标签: c# linq asp.net-mvc-4 ienumerable

我正在尝试在linq查询中添加其他where子句,具体取决于传递给函数的变量结果。

var allFeedback = 
    from f in _unitOfWork.Feedback.All()
    join b in _unitOfWork.Bookings.All() on f.CourseBookingID equals b.CourseBookingID
    join cb in _unitOfWork.CourseBookings.All() on f.CourseBookingID equals cb.CourseBookingID
    where b.SiteID == siteID && b.Date >= fromDate && b.Date <= to && b.CancelledID == null
    select f;

if (courseID > 0)
{
    allFeedback.Where(f => f.CourseBooking.CourseID == courseID);
}

if (facilitatorID == 0)
{
    allFeedback.Where(f => f.CourseBooking.FacilitatorID == null);
}
else if (facilitatorID > 0)
{
    allFeedback.Where(f => f.CourseBooking.FacilitatorID == facilitatorID);
}

allFeedback.ToList();

我想将where子句添加到原始查询“allFeedback”,但是当执行查询时,将忽略其他子句。

这可能吗?

1 个答案:

答案 0 :(得分:6)

是的,它可以做到:

if (courseID > 0)
{
    allFeedback = allFeedback.Where(f => f.CourseBooking.CourseID == courseID);
}

if (facilitatorID == 0)
{
    allFeedback = allFeedback.Where(f => f.CourseBooking.FacilitatorID == null);
}
else if (facilitatorID > 0)
{
    allFeedback = allFeedback.Where(f => f.CourseBooking.FacilitatorID == facilitatorID);
}

您忘了将结果分配给变量。