有条件的LINQ查询有条件、LINQ

2023-09-08 08:43:43 作者:山河不入梦

我们正努力在日志查看器。使用将可以选择按用户,严重程度等来过滤在SQL日子里,我想补充的查询字符串,但我想使用LINQ做到这一点。我如何能有条件地加入其中,从句?

We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?

推荐答案

如果你想,如果某些标准传递到只进行筛选,做这样的事情

if you want to only filter if certain criteria is passed, do something like this

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

否则,这样可以让你的前pression树正是你想要的。这样的SQL创建将是正是你需要的也不少。

Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.