如何有条件地应用 Linq 运算符? [英] How can I conditionally apply a Linq operator?

查看:29
本文介绍了如何有条件地应用 Linq 运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发日志查看器.使用将可以选择按用户、严重性等进行过滤.在 Sql 天我会添加到查询字符串,但我想用 Linq 来做.如何有条件地添加 where 子句?

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

这样做将使您的表达式树完全符合您的要求.这样创建的 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.

这篇关于如何有条件地应用 Linq 运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆