如果不是NULL,则添加where子句

时间:2013-07-07 13:31:40

标签: linq-to-sql entity-framework-4 linq-to-entities

这是我的查询:

    List<string> kwList = GetFilterKeywords(); // returns NULL none keyword selected
    var res = from d in ctx.Books
    where (kwList == null || kwList.Contains(d.Name))
    select d;

如果kwList为NULL,则看起来添加where子句是不合法的。所以我的问题是:有没有办法在IF / ELSE IF构造中为同一个查询添加更多where子句?

我的意思是:

    var res = from d in ctx.Books
              select d;
    if (kwList != null)
    {
       res.Where(d => kwList.Contains(d.Name);
    }

2 个答案:

答案 0 :(得分:0)

var res = ctx.Books; // no need to write select
if (kwList != null)
    res = res.Where(x => kwList.Contains(x.Name));

foreach (d in res) {
    ...
}

答案 1 :(得分:0)

您可以使用第三级运算符

var res = kwList == null ? ctx.Books : ctx.Books.Where(x => kwList.Contains(x.Name));

如果要在后续case语句中修改初始linq查询,请确保将初始查询重新分配给修改后的:

    var res = ctx.Books;
    if (a == b) 
    {
        // reassign here
        res = res.Where(x => kwList.Contains(x.Name));
    } 
    else if (a == c) 
       res = res.Where(x => x.Id == y);