代码之家  ›  专栏  ›  技术社区  ›  Alex Angas Colin

为什么这个LINQ WHERE子句不返回结果?

  •  1
  • Alex Angas Colin  · 技术社区  · 15 年前

    我们有一个具有datetime属性的实体 DateDestroyed . 查询需要返回介于可空日期时间之间的结果 startDate endDate .

    我有何条件:

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

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

    4 回复  |  直到 15 年前
        1
  •  0
  •   p.campbell    15 年前

    您可以为创建/使用扩展方法 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<T> IQueryable<T> .

        2
  •  1
  •   Community Mohan Dere    9 年前

    我的代码需要iqueryable,所以我根据 @p.campbell ExtensionMethod.net 如下:

    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;
    }
    
        3
  •  0
  •   Steve Michelotti    15 年前

    假设您有一个名为“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
  •  -1
  •   GONeale    15 年前

    您是否总是使用 Where() 过滤器应用?

    此模式应按预期工作:

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