<p>I've got a lot of ugly code that looks like this:</p>

<pre><code>if (!string.IsNullOrEmpty(ddlFileName.SelectedItem.Text))
    results = results.Where(x =&gt; x.FileName.Contains(ddlFileName.SelectedValue));
if (chkFileName.Checked)
    results = results.Where(x =&gt; x.FileName == null);

if (!string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text))
    results = results.Where(x =&gt; x.IpAddress.Contains(ddlIPAddress.SelectedValue));
if (chkIPAddress.Checked)
    results = results.Where(x =&gt; x.IpAddress == null);

...etc.
</code></pre>

<p><code>results</code> is an <code>IQueryable&lt;MyObject&gt;</code>.<br>
The idea is that for each of these innumerable dropdowns and checkboxes, if the dropdown has something selected, the user wants to match that item.  If the checkbox is checked, the user wants specifically those records where that field is null or an empty string.  (The UI doesn't let both be selected at the same time.)  This all adds to the LINQ Expression which gets executed at the end, after we've added all the conditions.</p>

<p>It <em>seems</em> like there ought to be some way to pull out an <code>Expression&lt;Func&lt;MyObject, bool&gt;&gt;</code> or two so that I can put the repeated parts in a method and just pass in what changes.  I've done this in other places, but this set of code has me stymied.  (Also, I'd like to avoid "Dynamic LINQ", because I want to keep things type-safe if possible.)  Any ideas?</p>

[{'answer_id': 54981, 'author': 'bdukes', 'author_id': 2688, 'author_profile': 'https://Stackoverflow.com/users/2688', 'pm_score': 0, 'selected': False, 'text': '<pre><code>results = results.Where(x =&gt; \n    (string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) || x.FileName.Contains(ddlFileName.SelectedValue))\n    &amp;&amp; (!chkFileName.Checked || string.IsNullOrEmpty(x.FileName))\n    &amp;&amp; ...);\n</code></pre>\n'}, {'answer_id': 55069, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': "<p>I'd convert it into a single Linq statement:</p>\n\n<pre><code>var results =\n    //get your inital results\n    from x in GetInitialResults()\n    //either we don't need to check, or the check passes\n    where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n       x.FileName.Contains(ddlFileName.SelectedValue)\n    where !chkFileName.Checked ||\n       string.IsNullOrEmpty(x.FileName)\n    where string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n       x.FileName.Contains(ddlIPAddress.SelectedValue)\n    where !chkIPAddress.Checked ||\n       string.IsNullOrEmpty(x. IpAddress)\n    select x;\n</code></pre>\n\n<p>It's no shorter, but I find this logic clearer.</p>\n"}, {'answer_id': 55443, 'author': 'Ryan Lundy', 'author_id': 5486, 'author_profile': 'https://Stackoverflow.com/users/5486', 'pm_score': 0, 'selected': False, 'text': "<p>Neither of these answers so far is quite what I'm looking for.  To give an example of what I'm aiming at (I don't regard this as a complete answer either), I took the above code and created a couple of extension methods:</p>\n\n<pre><code>static public IQueryable&lt;Activity&gt; AddCondition(\n    this IQueryable&lt;Activity&gt; results,\n    DropDownList ddl, \n    Expression&lt;Func&lt;Activity, bool&gt;&gt; containsCondition)\n{\n    if (!string.IsNullOrEmpty(ddl.SelectedItem.Text))\n        results = results.Where(containsCondition);\n    return results;\n}\nstatic public IQueryable&lt;Activity&gt; AddCondition(\n    this IQueryable&lt;Activity&gt; results,\n    CheckBox chk, \n    Expression&lt;Func&lt;Activity, bool&gt;&gt; emptyCondition)\n{\n    if (chk.Checked)\n        results = results.Where(emptyCondition);\n    return results;\n}\n</code></pre>\n\n<p>This allowed me to refactor the code above into this:</p>\n\n<pre><code>results = results.AddCondition(ddlFileName, x =&gt; x.FileName.Contains(ddlFileName.SelectedValue));\nresults = results.AddCondition(chkFileName, x =&gt; x.FileName == null || x.FileName.Equals(string.Empty));\n\nresults = results.AddCondition(ddlIPAddress, x =&gt; x.IpAddress.Contains(ddlIPAddress.SelectedValue));\nresults = results.AddCondition(chkIPAddress, x =&gt; x.IpAddress == null || x.IpAddress.Equals(string.Empty));\n</code></pre>\n\n<p>This isn't <em>quite</em> as ugly, but it's still longer than I'd prefer.  The pairs of lambda expressions in each set are obviously very similar, but I can't figure out a way to condense them further...at least not without resorting to dynamic LINQ, which makes me sacrifice type safety.</p>\n\n<p>Any other ideas?</p>\n"}, {'answer_id': 55490, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 0, 'selected': False, 'text': '<p>@Kyralessa,</p>\n\n<p>You can create extension method AddCondition for predicates that accepts parameter of type Control plus lambda expression and returns combined expression. Then you can combine conditions using fluent interface and reuse your predicates. To see example of how it can be implemented see my answer on this question:</p>\n\n<p><a href="https://stackoverflow.com/questions/53597/how-do-i-compose-existing-linq-expressions">How do I compose existing Linq Expressions</a></p>\n'}, {'answer_id': 55955, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 3, 'selected': False, 'text': "<p>In that case:</p>\n\n<pre><code>//list of predicate functions to check\nvar conditions = new List&lt;Predicate&lt;MyClass&gt;&gt; \n{\n    x =&gt; string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n         x.FileName.Contains(ddlFileName.SelectedValue),\n    x =&gt; !chkFileName.Checked ||\n         string.IsNullOrEmpty(x.FileName),\n    x =&gt; string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n         x.IpAddress.Contains(ddlIPAddress.SelectedValue),\n    x =&gt; !chkIPAddress.Checked ||\n         string.IsNullOrEmpty(x.IpAddress)\n}\n\n//now get results\nvar results =\n    from x in GetInitialResults()\n    //all the condition functions need checking against x\n    where conditions.All( cond =&gt; cond(x) )\n    select x;\n</code></pre>\n\n<p>I've just explicitly declared the predicate list, but these could be generated, something like:</p>\n\n<pre><code>ListBoxControl lbc;\nCheckBoxControl cbc;\nforeach( Control c in this.Controls)\n    if( (lbc = c as ListBoxControl ) != null )\n         conditions.Add( ... );\n    else if ( (cbc = c as CheckBoxControl ) != null )\n         conditions.Add( ... );\n</code></pre>\n\n<p>You would need some way to check the property of MyClass that you needed to check, and for that you'd have to use reflection.</p>\n"}, {'answer_id': 56014, 'author': 'Ant', 'author_id': 3709, 'author_profile': 'https://Stackoverflow.com/users/3709', 'pm_score': 1, 'selected': False, 'text': '<p>Have you seen the <a href="http://www.albahari.com/nutshell/linqkit.html" rel="nofollow noreferrer">LINQKit</a>? The AsExpandable sounds like what you\'re after (though you may want to read the post <a href="http://tomasp.net/blog/linq-expand.aspx" rel="nofollow noreferrer">Calling functions in LINQ queries</a> at TomasP.NET for more depth).</p>\n'}, {'answer_id': 130791, 'author': 'Robert Paulson', 'author_id': 14033, 'author_profile': 'https://Stackoverflow.com/users/14033', 'pm_score': 0, 'selected': False, 'text': "<p>I'd be wary of the solutions of the form:</p>\n\n<pre><code>// from Keith\nfrom x in GetInitialResults()\n    //either we don't need to check, or the check passes\n    where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n       x.FileName.Contains(ddlFileName.SelectedValue)\n</code></pre>\n\n<p>My reasoning is variable capture. If you're immediately execute just the once you probably won't notice a difference. However, in linq, evaluation isn't immediate but happens each time iterated occurs. Delegates can capture variables and use them outside the scope you intended.</p>\n\n<p>It feels like you're querying too close to the UI. Querying is a layer down, and linq isn't the way for the UI to communicate down.</p>\n\n<p>You may be better off doing the following. Decouple the searching logic from the presentation - it's more flexible and reusable - fundamentals of OO. </p>\n\n<pre><code>// my search parameters encapsulate all valid ways of searching.\npublic class MySearchParameter\n{\n    public string FileName { get; private set; }\n    public bool FindNullFileNames { get; private set; }\n    public void ConditionallySearchFileName(bool getNullFileNames, string fileName)\n    {\n        FindNullFileNames = getNullFileNames;\n        FileName = null;\n\n        // enforce either/or and disallow empty string\n        if(!getNullFileNames &amp;&amp; !string.IsNullOrEmpty(fileName) )\n        {\n            FileName = fileName;\n        }\n    }\n    // ...\n}\n\n// search method in a business logic layer.\npublic IQueryable&lt;MyClass&gt; Search(MySearchParameter searchParameter)\n{\n    IQueryable&lt;MyClass&gt; result = ...; // something to get the initial list.\n\n    // search on Filename.\n    if (searchParameter.FindNullFileNames)\n    {\n        result = result.Where(o =&gt; o.FileName == null);\n    }\n    else if( searchParameter.FileName != null )\n    {   // intermixing a different style, just to show an alternative.\n        result = from o in result\n                 where o.FileName.Contains(searchParameter.FileName)\n                 select o;\n    }\n    // search on other stuff...\n\n    return result;\n}\n\n// code in the UI ... \nMySearchParameter searchParameter = new MySearchParameter();\nsearchParameter.ConditionallySearchFileName(chkFileNames.Checked, drpFileNames.SelectedItem.Text);\nsearchParameter.ConditionallySearchIPAddress(chkIPAddress.Checked, drpIPAddress.SelectedItem.Text);\n\nIQueryable&lt;MyClass&gt; result = Search(searchParameter);\n\n// inform control to display results.\nsearchResults.Display( result );\n</code></pre>\n\n<p>Yes it's more typing, but you read code around 10x more than you write it. Your UI is clearer, the search parameters class takes care of itself and ensures mutually exclusive options don't collide, and the search code is abstracted away from any UI and doesn't even care if you use Linq at all.</p>\n"}, {'answer_id': 132157, 'author': 'hurst', 'author_id': 10991, 'author_profile': 'https://Stackoverflow.com/users/10991', 'pm_score': 0, 'selected': False, 'text': '<p>Since you are wanting to repeatedly reduce the original results query with innumerable filters, you can use <strong>Aggregate()</strong>, (which corresponds to reduce() in functional languages).</p>\n\n<p>The filters are of predictable form, consisting of two values for every member of MyObject - according to the information I gleaned from your post. If every member to be compared is a string, which may be null, then I recommend using an extension method, which allows for null references to be associated to an extension method of its intended type.</p>\n\n<pre><code>public static class MyObjectExtensions\n{\n    public static bool IsMatchFor(this string property, string ddlText, bool chkValue)\n    {\n        if(ddlText!=null &amp;&amp; ddlText!="")\n        {\n            return property!=null &amp;&amp; property.Contains(ddlText);\n        }\n        else if(chkValue==true)\n        {\n            return property==null || property=="";\n        }\n        // no filtering selected\n        return true;\n    }\n}\n</code></pre>\n\n<p>We now need to arrange the property filters in a collection, to allow for iterating over many. They are represented as Expressions for compatibility with IQueryable.</p>\n\n<pre><code>var filters = new List&lt;Expression&lt;Func&lt;MyObject,bool&gt;&gt;&gt;\n{\n    x=&gt;x.Filename.IsMatchFor(ddlFileName.SelectedItem.Text,chkFileName.Checked),\n    x=&gt;x.IPAddress.IsMatchFor(ddlIPAddress.SelectedItem.Text,chkIPAddress.Checked),\n    x=&gt;x.Other.IsMatchFor(ddlOther.SelectedItem.Text,chkOther.Checked),\n    // ... innumerable associations\n};\n</code></pre>\n\n<p>Now we aggregate the innumerable filters onto the initial results query:</p>\n\n<pre><code>var filteredResults = filters.Aggregate(results, (r,f) =&gt; r.Where(f));\n</code></pre>\n\n<p>I ran this in a console app with simulated test values, and it worked as expected. I think this at least demonstrates the principle.</p>\n'}, {'answer_id': 142632, 'author': 'Emperor XLII', 'author_id': 2495, 'author_profile': 'https://Stackoverflow.com/users/2495', 'pm_score': 0, 'selected': False, 'text': '<p>One thing you might consider is simplifying your UI by eliminating the checkboxes and using an "<code>&lt;empty&gt;</code>" or "<code>&lt;null&gt;</code>" item in your drop down list instead. This would reduce the number of controls taking up space on your window, remove the need for complex "enable X only if Y is not checked" logic, and would enable a nice one-control-per-query-field.</p>\n\n<p><br/>\nMoving on to your result query logic, I would start by creating a simple object to represent a filter on your domain object:</p>\n\n<pre><code>interface IDomainObjectFilter {\n  bool ShouldInclude( DomainObject o, string target );\n}\n</code></pre>\n\n<p>You can associate an appropriate instance of the filter with each of your UI controls, and then retrieve that when the user initiates a query:</p>\n\n<pre><code>sealed class FileNameFilter : IDomainObjectFilter {\n  public bool ShouldInclude( DomainObject o, string target ) {\n    return string.IsNullOrEmpty( target )\n        || o.FileName.Contains( target );\n  }\n}\n\n...\nddlFileName.Tag = new FileNameFilter( );\n</code></pre>\n\n<p>You can then generalize your result filtering by simply enumerating your controls and executing the associated filter (thanks to <a href="https://stackoverflow.com/questions/54963/how-would-you-refactor-this-linq-code#132157">hurst</a> for the Aggregate idea):</p>\n\n<pre><code>var finalResults = ddlControls.Aggregate( initialResults, ( c, r ) =&gt; {\n  var filter = c.Tag as IDomainObjectFilter;\n  var target = c.SelectedValue;\n  return r.Where( o =&gt; filter.ShouldInclude( o, target ) );\n} );\n</code></pre>\n\n<p><br/>\nSince your queries are so regular, you might be able to simplify the implementation even further by using a single filter class taking a member selector:</p>\n\n<pre><code>sealed class DomainObjectFilter {\n  private readonly Func&lt;DomainObject,string&gt; memberSelector_;\n  public DomainObjectFilter( Func&lt;DomainObject,string&gt; memberSelector ) {\n    this.memberSelector_ = memberSelector;\n  }\n\n  public bool ShouldInclude( DomainObject o, string target ) {\n    string member = this.memberSelector_( o );\n    return string.IsNullOrEmpty( target )\n        || member.Contains( target );\n  }\n}\n\n...\nddlFileName.Tag = new DomainObjectFilter( o =&gt; o.FileName );\n</code></pre>\n'}, {'answer_id': 142688, 'author': 'loudej', 'author_id': 6056, 'author_profile': 'https://Stackoverflow.com/users/6056', 'pm_score': 1, 'selected': False, 'text': "<p>Don't use LINQ if it's impacting readability. Factor out the individual tests into boolean methods which can be used as your where expression.</p>\n\n<pre><code>IQueryable&lt;MyObject&gt; results = ...;\n\nresults = results\n    .Where(TestFileNameText)\n    .Where(TestFileNameChecked)\n    .Where(TestIPAddressText)\n    .Where(TestIPAddressChecked);\n</code></pre>\n\n<p>So the the individual tests are simple methods on the class. They're even individually unit testable. </p>\n\n<pre><code>bool TestFileNameText(MyObject x)\n{\n    return string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n           x.FileName.Contains(ddlFileName.SelectedValue);\n}\n\nbool TestIPAddressChecked(MyObject x)\n{\n    return !chkIPAddress.Checked ||\n        x.IpAddress == null;\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/54963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5486/']