6

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?

Community
  • 1
  • 1
silent
  • 3,964
  • 5
  • 27
  • 29
  • I have looked at the answer and I think that this method - while it may be less efficient is certainly a lot better from a type safety point of view. After all, for a start, LINQ was designed to avoid dynamic queries, so it's kind of pointless and secondly it is always prone to SQL Injection if you're not careful. – Andrea Raimondi Sep 27 '15 at 05:25

2 Answers2

5

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.

Nestor
  • 2,753
  • 2
  • 29
  • 34
2

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

Matin Habibi
  • 700
  • 1
  • 8
  • 20