Linq条件Where子句

sil*_*ent 5 linq-to-sql

在搜索linq条件where子句时,我发现了这篇文章,他们使用的方式如下:

var logs = from log in context.Logs
           select log;

if (filterBySeverity)
    logs = logs.Where(p => p.Severity == severity);

if (filterByUser)
    logs = logs.Where(p => p.User == user);
Run Code Online (Sandbox Code Playgroud)

但我想知道这种方法有效吗?linq会执行多少次查询?

Nes*_*tor 5

是的,我认为这是有效的.此代码实际上不会执行任何查询,因为它不会尝试从"日志"中读取任何内容.如果是这样,它应该在同一个查询中考虑这两个条件(即包含两个条件的WHERE子句).

但是,如果您正在使用LINQ并担心效率,那么您必须使用工具检查您编写的所有内容,以查看实际运行的查询.您可以使用SQL Server Profiler执行此操作.


Mat*_*ibi 2

您可以使用动态 LINQ(ScottGu 的文章

因此,您可以轻松地在字符串中创建 where 子句,然后将其传递给Where 方法:

public string GetWhereClause()
{
string whereClause = "";
....
return whereClause
}

var logs = context.Logs.Where( GetWhereClause() );
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 ;)

  • 与我提供的代码相比,您认为哪种方式更有效? (2认同)