<p>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?</p>

[{'answer_id': 11201, 'author': 'TheSmurf', 'author_id': 1975282, 'author_profile': 'https://Stackoverflow.com/users/1975282', 'pm_score': 0, 'selected': False, 'text': '<p>Just use C#\'s &amp;&amp; operator:</p>\n\n<pre><code>var items = dc.Users.Where(l =&gt; l.Date == DateTime.Today &amp;&amp; l.Severity == "Critical")\n</code></pre>\n\n<p>Edit: Ah, need to read more carefully. You wanted to know how to <em>conditionally</em> add additional clauses. In that case, I have no idea. :) What I\'d probably do is just prepare several queries, and execute the right one, depending on what I ended up needing.</p>\n'}, {'answer_id': 11203, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 8, 'selected': True, 'text': '<p>if you want to only filter if certain criteria is passed, do something like this</p>\n\n<pre><code>var logs = from log in context.Logs\n           select log;\n\nif (filterBySeverity)\n    logs = logs.Where(p =&gt; p.Severity == severity);\n\nif (filterByUser)\n    logs = logs.Where(p =&gt; p.User == user);\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 11204, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 0, 'selected': False, 'text': "<p>You could use an external method:</p>\n\n<pre><code>var results =\n    from rec in GetSomeRecs()\n    where ConditionalCheck(rec)\n    select rec;\n\n...\n\nbool ConditionalCheck( typeofRec input ) {\n    ...\n}\n</code></pre>\n\n<p>This would work, but can't be broken down into expression trees, which means Linq to SQL would run the check code against every record.</p>\n\n<p>Alternatively:</p>\n\n<pre><code>var results =\n    from rec in GetSomeRecs()\n    where \n        (!filterBySeverity || rec.Severity == severity) &amp;&amp;\n        (!filterByUser|| rec.User == user)\n    select rec;\n</code></pre>\n\n<p>That might work in expression trees, meaning Linq to SQL would be optimised.</p>\n"}, {'answer_id': 11225, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 0, 'selected': False, 'text': '<p>Well, what I thought was you could put the filter conditions into a generic list of Predicates:</p>\n\n<pre><code>    var list = new List&lt;string&gt; { "me", "you", "meyou", "mow" };\n\n    var predicates = new List&lt;Predicate&lt;string&gt;&gt;();\n\n    predicates.Add(i =&gt; i.Contains("me"));\n    predicates.Add(i =&gt; i.EndsWith("w"));\n\n    var results = new List&lt;string&gt;();\n\n    foreach (var p in predicates)\n        results.AddRange(from i in list where p.Invoke(i) select i);               \n</code></pre>\n\n<p>That results in a list containing "me", "meyou", and "mow".</p>\n\n<p>You could optimize that by doing the foreach with the predicates in a totally different function that ORs all the predicates.</p>\n'}, {'answer_id': 11241, 'author': 't3rse', 'author_id': 64, 'author_profile': 'https://Stackoverflow.com/users/64', 'pm_score': 1, 'selected': False, 'text': "<p>It isn't the prettiest thing but you can use a lambda expression and pass your conditions optionally. In TSQL I do a lot of the following to make parameters optional: </p>\n\n<blockquote>\n  <p>WHERE Field = @FieldVar OR @FieldVar IS NULL</p>\n</blockquote>\n\n<p>You could duplicate the same style with a the following lambda (an example of checking authentication): </p>\n\n<blockquote>\n  <p>MyDataContext db = new MyDataContext();</p>\n  \n  <p>void RunQuery(string param1, string param2, int? param3){</p>\n  \n  <blockquote>\n    <p>Func checkUser = user => </p>\n    \n    <blockquote>\n      <p>((param1.Length > 0)? user.Param1 == param1 : 1 == 1) &amp;&amp;</p>\n      \n      <p>((param2.Length > 0)? user.Param2 == param2 : 1 == 1) &amp;&amp; </p>\n      \n      <p>((param3 != null)? user.Param3 == param3 : 1 == 1);</p>\n    </blockquote>\n    \n    <p>User foundUser = db.Users.SingleOrDefault(checkUser);</p>\n  </blockquote>\n  \n  <p>}</p>\n</blockquote>\n"}, {'answer_id': 11729, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 4, 'selected': False, 'text': '<p>When it comes to conditional linq, I am very fond of the filters and pipes pattern.<br>\n<a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-3/" rel="noreferrer">http://blog.wekeroad.com/mvc-storefront/mvcstore-part-3/</a></p>\n\n<p>Basically you create an extension method for each filter case that takes in the IQueryable and a parameter.</p>\n\n<pre><code>public static IQueryable&lt;Type&gt; HasID(this IQueryable&lt;Type&gt; query, long? id)\n{\n    return id.HasValue ? query.Where(o =&gt; i.ID.Equals(id.Value)) : query;\n}\n</code></pre>\n'}, {'answer_id': 11769, 'author': 'Brad Leach', 'author_id': 708, 'author_profile': 'https://Stackoverflow.com/users/708', 'pm_score': 2, 'selected': False, 'text': '<p>Another option would be to use something like the PredicateBuilder discussed <a href="http://www.albahari.com/nutshell/predicatebuilder.html" rel="nofollow noreferrer">here</a>.\nIt allows you to write code like the following:</p>\n\n<pre><code>var newKids  = Product.ContainsInDescription ("BlackBerry", "iPhone");\n\nvar classics = Product.ContainsInDescription ("Nokia", "Ericsson")\n                  .And (Product.IsSelling());\n\nvar query = from p in Data.Products.Where (newKids.Or (classics))\n            select p;\n</code></pre>\n\n<p>Note that I\'ve only got this to work with Linq 2 SQL. EntityFramework does not implement Expression.Invoke, which is required for this method to work. I have a question regarding this issue <a href="https://stackoverflow.com/questions/10524/expressioninvoke-in-entity-framework">here</a>.</p>\n'}, {'answer_id': 14560, 'author': 'Andy Rose', 'author_id': 1762, 'author_profile': 'https://Stackoverflow.com/users/1762', 'pm_score': 1, 'selected': False, 'text': '<p>I had a similar requirement recently and eventually found this in he MSDN.\n<a href="http://code.msdn.microsoft.com/csharpsamples" rel="nofollow noreferrer">CSharp Samples for Visual Studio 2008</a></p>\n\n<p>The classes included in the DynamicQuery sample of the download allow you to create dynamic queries at runtime in the following format:</p>\n\n<pre><code>var query =\ndb.Customers.\nWhere("City = @0 and Orders.Count &gt;= @1", "London", 10).\nOrderBy("CompanyName").\nSelect("new(CompanyName as Name, Phone)");\n</code></pre>\n\n<p>Using this you can build a query string dynamically at runtime and pass it into the Where() method:</p>\n\n<pre><code>string dynamicQueryString = "City = \\"London\\" and Order.Count &gt;= 10"; \nvar q = from c in db.Customers.Where(queryString, null)\n        orderby c.CompanyName\n        select c;\n</code></pre>\n'}, {'answer_id': 19950, 'author': 'sgwill', 'author_id': 1204, 'author_profile': 'https://Stackoverflow.com/users/1204', 'pm_score': 4, 'selected': False, 'text': "<p>I ended using an answer similar to Daren's, but with an IQueryable interface:</p>\n\n<pre><code>IQueryable&lt;Log&gt; matches = m_Locator.Logs;\n\n// Users filter\nif (usersFilter)\n    matches = matches.Where(l =&gt; l.UserName == comboBoxUsers.Text);\n\n // Severity filter\n if (severityFilter)\n     matches = matches.Where(l =&gt; l.Severity == comboBoxSeverity.Text);\n\n Logs = (from log in matches\n         orderby log.EventTime descending\n         select log).ToList();\n</code></pre>\n\n<p>That builds up the query before hitting the database. The command won't run until .ToList() at the end.</p>\n"}, {'answer_id': 5941594, 'author': 'Carlos', 'author_id': 745725, 'author_profile': 'https://Stackoverflow.com/users/745725', 'pm_score': 5, 'selected': False, 'text': '<p>If you need to filter base on a List / Array use the following:</p>\n\n<pre><code>    public List&lt;Data&gt; GetData(List&lt;string&gt; Numbers, List&lt;string&gt; Letters)\n    {\n        if (Numbers == null)\n            Numbers = new List&lt;string&gt;();\n\n        if (Letters == null)\n            Letters = new List&lt;string&gt;();\n\n        var q = from d in database.table\n                where (Numbers.Count == 0 || Numbers.Contains(d.Number))\n                where (Letters.Count == 0 || Letters.Contains(d.Letter))\n                select new Data\n                {\n                    Number = d.Number,\n                    Letter = d.Letter,\n                };\n        return q.ToList();\n\n    }\n</code></pre>\n'}, {'answer_id': 6330322, 'author': 'James Livingston', 'author_id': 145966, 'author_profile': 'https://Stackoverflow.com/users/145966', 'pm_score': 3, 'selected': False, 'text': '<p>Doing this:</p>\n\n<pre><code>bool lastNameSearch = true/false; // depending if they want to search by last name,\n</code></pre>\n\n<p>having this in the <code>where</code> statement:</p>\n\n<pre><code>where (lastNameSearch &amp;&amp; name.LastNameSearch == "smith")\n</code></pre>\n\n<p>means that when the final query is created, if <code>lastNameSearch</code> is <code>false</code> the query will completely omit any SQL for the last name search.</p>\n'}, {'answer_id': 51278965, 'author': 'Ryan', 'author_id': 2266345, 'author_profile': 'https://Stackoverflow.com/users/2266345', 'pm_score': 4, 'selected': False, 'text': "<p>I solved this with an extension method to allow LINQ to be conditionally enabled in the middle of a fluent expression. This removes the need to break up the expression with <code>if</code> statements.</p>\n\n<p><code>.If()</code> extension method:</p>\n\n<pre><code>public static IQueryable&lt;TSource&gt; If&lt;TSource&gt;(\n        this IQueryable&lt;TSource&gt; source,\n        bool condition,\n        Func&lt;IQueryable&lt;TSource&gt;, IQueryable&lt;TSource&gt;&gt; branch)\n    {\n        return condition ? branch(source) : source;\n    }\n</code></pre>\n\n<p>This allows you to do this:</p>\n\n<pre><code>return context.Logs\n     .If(filterBySeverity, q =&gt; q.Where(p =&gt; p.Severity == severity))\n     .If(filterByUser, q =&gt; q.Where(p =&gt; p.User == user))\n     .ToList();\n</code></pre>\n\n<p>Here's also an <code>IEnumerable&lt;T&gt;</code> version which will handle most other LINQ expressions:</p>\n\n<pre><code>public static IEnumerable&lt;TSource&gt; If&lt;TSource&gt;(\n    this IEnumerable&lt;TSource&gt; source,\n    bool condition,\n    Func&lt;IEnumerable&lt;TSource&gt;, IEnumerable&lt;TSource&gt;&gt; branch)\n    {\n        return condition ? branch(source) : source;\n    }\n</code></pre>\n"}, {'answer_id': 55732512, 'author': 'Gustavo', 'author_id': 6672759, 'author_profile': 'https://Stackoverflow.com/users/6672759', 'pm_score': 1, 'selected': False, 'text': '<p>You can create and use this extension method</p>\n\n<pre><code>public static IQueryable&lt;TSource&gt; WhereIf&lt;TSource&gt;(this IQueryable&lt;TSource&gt; source, bool isToExecute, Expression&lt;Func&lt;TSource, bool&gt;&gt; predicate)\n{\n    return isToExecute ? source.Where(predicate) : source;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/11194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204/']