Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I conditionally apply a Linq operator?

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?

like image 495
sgwill Avatar asked Aug 14 '08 15:08

sgwill


People also ask

Which clause is used for conditions in LINQ?

LINQ Where Clause with Query Syntax We can use a filtering operator where clause in query syntax to filter list/collection data based on conditions.

Can we use ternary operator in LINQ query?

We can simply use a ternary operator or we can even use a nested ternary operator.


1 Answers

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

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.

like image 99
Darren Kopp Avatar answered Sep 18 '22 13:09

Darren Kopp