将.Where(..)附加到Linq.IQueryable

时间:2014-03-10 20:04:00

标签: c# linq

我正在构建Linq IQueryable并希望根据特定条件添加不同的.Where()参数。在运行时,似乎没有考虑附加的.Where()。怎么可能做错了?

var query = Context.Sessions
   .Where(s => s.UserID.Equals(currentUserID))
   .Where(s => s.ClosedTime.HasValue)
   .Where(s => !s.ApprovedTime.HasValue);

if (type == Models.EnvironmentType.A)
{
   query.Where(s => s.BedroomID.HasValue);
}
else if (type == Models.EnvironmentType.B)
{
   query.Where(s => s.HomeID.HasValue);
}

谢谢!

2 个答案:

答案 0 :(得分:9)

您需要将返回的结果分配回查询。Where创建一个新查询,它不会更改原始查询。

query = query.Where(s => s.BedroomID.HasValue);

答案 1 :(得分:1)

query.Where(s => s.BedroomID.HasValue)只会产生一个查询,它不会改变现有的query

您需要将其分配给现有查询:

query = query.Where(s => s.BedroomID.HasValue);
相关问题