Reputation: 4004
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?
Upvotes: 6
Views: 7866
Reputation:
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.
Upvotes: 5
Reputation: 700
You can use dynamic LINQ (ScottGu's Article)
So you can easily create your where clause in string and then pass it to the Where method:
public string GetWhereClause()
{
string whereClause = "";
....
return whereClause
}
var logs = context.Logs.Where( GetWhereClause() );
Hope this helps ;)
Upvotes: 2