繁体   English   中英

Linq查询生成器

[英]Linq query builder

我有一个Linq查询:

from c in table where id = 1

但是有时候我只需要

from c in table 

恢复所有记录。

是否可以执行以下操作:

From c in table
if (!id == 0)
{
    where id = 1
}

或是否必须编写代码

if (!id == 0)
{
    from c in table where id = id
}
else
{
    from c in table 
}

为什么不使用:

var records = db.table;
if(id != 0)
    records = db.table.Where(r => r.id == id);

由于LINQ的执行延迟,因此第一条语句不会查询数据库。

由于您似乎更喜欢查询语法:

var records = db.table;
if(id != 0)
    records = from rec in db.table
              where rec.id == id
              select rec;

除了Tim的答复外,我已经看到和使用的是在不需要其他where子句的情况下使用“虚拟” where true表达式,因此您可以使用单个表达式:

from c in table where id != 0 ? c.Id == id : true select c;

我看不出有什么弊端,即使看起来更加令人困惑。 当然,您需要了解速记表达。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM