Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Conditional Where clause

Tags:

linq-to-sql

While searching for linq conditional where clause, I found this article, the way they use is like below:

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

but I was wondering is this method efficient? How many queries would linq perform?

like image 486
silent Avatar asked Oct 26 '09 07:10

silent


1 Answers

Yes, I think this is efficient. No queries will actually be performed by this code, because it doesn't try to read anything from 'logs'. When it does, it should take both conditions into account in the same query (i.e. a WHERE clause that includes both conditions).

BUT, if you are using LINQ and worried about efficiency, you really have to check everything you write by using tools to look at what queries actually get run. You can do this using SQL Server Profiler.

like image 67
Nestor Avatar answered Oct 09 '22 13:10

Nestor