0

这是我的查询:

    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);
    }
4

2 回答 2

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) {
    ...
}
于 2013-07-07T13:45:23.423 回答
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);  
于 2013-07-07T19:28:32.753 回答