【问题标题】:Why is this LINQ Where clause not returning results?为什么这个 LINQ Where 子句不返回结果?
【发布时间】:2010-09-08 08:56:52
【问题描述】:

我们有一个具有 DateTime 属性 DateDestroyed 的实体。查询需要返回此值介于可为空的 DateTimes startDateendDate 之间的结果。

我的 where 子句是:

.Where(x => startDate.HasValue ? startDate <= x.DateDestroyed : true)
.Where(x => endDate.HasValue ? x.DateDestroyed <= endDate : true);

查询始终不返回任何结果。我很确定我没有正确编写此查询,但不知道应该如何编写或为什么它不起作用?

【问题讨论】:

  • 你是否只使用其中一个 where 得到结果?
  • 你是在查询组成后更改startDateendDate的值吗?
  • 这些答案对您有帮助吗?似乎有一个开车通过的downvoter。

标签: linq linq-to-objects


【解决方案1】:

我的代码需要 IQueryable,因此我在 ExtensionMethod.net 处修改了 @p.campbell 的工作,如下所示:

public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, bool> predicate)
{
    return condition ? source.Where(predicate).AsQueryable() : source;
}

public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Func<TSource, int, bool> predicate)
{
    return condition ? source.Where(predicate).AsQueryable() : source;
}

【讨论】:

    【解决方案2】:

    您可以为WhereIf 创建/使用扩展方法:

    给定一个布尔条件,附加一个Where 子句。

     var foo = db.Customers.WhereIf(startDate.HasValue, 
                                       x => startDate <= x.DateDestroyed)
                           .WhereIf(endDate.HasValue,  
                                       x => x.DateDestroyed <= endDate );
    

    更多详情请访问WhereIf at ExtensionMethod.net。您可以在那里找到IEnumerable&lt;T&gt;IQueryable&lt;T&gt; 的代码。

    【讨论】:

    • @randomDownvoter:想解释一下你的反对意见以及这个答案如何无助于解决问题?
    • 我得到了同样的东西 p.campbell,我很确定我的回答也会奏效。 :(
    【解决方案3】:

    假设您有一个名为“query”的变量,您存储了 linq 语句的开头部分。试试这个动态构造 where 子句:

    if (startDate.HasValue) {
        query = query.Where(x => x.DateDestroyed >= startDate);
    }
    if (endDate.HasValue) {
        query = query.Where(x => x.DateDestroyed <= endDate);
    }
    

    LINQ 适用于延迟执行,因此 WHERE 子句将在代码执行时正确解析。

    【讨论】:

      【解决方案4】:

      您是否总是在应用Where() 过滤器的情况下重新分配查询?

      这种模式应该可以按预期工作:

      var query = getResults();
      query = query.Where(x => startDate.HasValue ? startDate <= x.DateDestroyed : true)
      query = query.Where(x => endDate.HasValue ? x.DateDestroyed <= endDate : true);
      

      【讨论】:

      • 我一直使用这种模式,它应该可以工作.. ?你投了反对票吗?我认为我的建议不值得投反对票。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多