条件Linq查询

我们正在研究一个日志查看器。使用时可以选择按用户,严重性等进行过滤。在Sql天内,我将添加到查询字符串中,但是我想使用Linq进行过滤。如何有条件地添加子句?



DIEA
浏览 439回答 3
3回答

慕村9548890

如果您只想过滤通过特定条件的情况,请执行以下操作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正是您所需要的,而且仅此而已。

aluckdog

我使用了类似于达人的答案,但是有了一个IQueryable接口:IQueryable<Log> matches = m_Locator.Logs;// Users filterif (usersFilter)&nbsp; &nbsp; matches = matches.Where(l => l.UserName == comboBoxUsers.Text);&nbsp;// Severity filter&nbsp;if (severityFilter)&nbsp; &nbsp; &nbsp;matches = matches.Where(l => l.Severity == comboBoxSeverity.Text);&nbsp;Logs = (from log in matches&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;orderby log.EventTime descending&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;select log).ToList();这将在命中数据库之前建立查询。该命令直到.ToList()最后才运行。
打开App,查看更多内容
随时随地看视频慕课网APP