{"id":1725,"date":"2013-11-15T00:00:00","date_gmt":"2013-11-15T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/giving-clarity-to-linq-queries-by-extending-expressions\/"},"modified":"2026-04-15T18:20:51","modified_gmt":"2026-04-15T18:20:51","slug":"giving-clarity-to-linq-queries-by-extending-expressions","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/giving-clarity-to-linq-queries-by-extending-expressions\/","title":{"rendered":"LINQ Expression Trees and IQueryable Extensions: Building Composable Filters"},"content":{"rendered":"\n<div id=\"pretty\">\n<h2>Executive Summary<\/h2>\n<p><strong>Complex LINQ queries that chain multiple conditions in a single Where clause become difficult to read, reuse, and test as requirements grow. This article demonstrates two techniques for building composable, self-describing LINQ query filters: (1) IQueryable extension methods using the Pipe and Filter pattern &#8211; each filter is a named extension method that encapsulates one condition, making queries readable as a chain of intent rather than a lambda expression. (2) Expression tree composition using Expression.AndAlso and Expression.OrElse &#8211; combining predicate expressions at the type level rather than at the query level, enabling dynamic filter construction from multiple independently-defined predicates. Both techniques work with Entity Framework and any LINQ provider that translates IQueryable to SQL.<\/strong><\/p>\n<h1>Overview<\/h1>\n<p class=\"start\">LINQ and Entity Framework are both commonly used in the <strong>.Net<\/strong> ecosystem, but even well-written applications can have LINQ queries that are difficult to understand. Because LINQ is so flexible, it can be written in ways that fail to communicate the developer&#8217;s intent. Well-written LINQ should be so clear as to be self-documenting. To write clear LINQ, it helps to understand the details of a few LINQ components that improve LINQ&#8217;s readability.<\/p>\n<p>We&#8217;ll be showing how to use a pipe, filter and rule pattern to make LINQ queries easier to comprehend. We&#8217;ll start by taking a look at how we can extend the <code>Where<\/code> method by creating custom filters that take advantage of <code>IQueryable<\/code> extension methods. Finally we will take a deep dive into <strong>expression trees<\/strong> to understand how they work, and how to manipulate them for maximum reusability.<\/p>\n<h2>Where the problem lies<\/h2>\n<p>The LINQ API allows several different styles of programming. The API allows us to chain together multiple methods, each of which can take elaborate lambda expressions, but by using this style, we can lose sight of the actual purpose of the code.<\/p>\n<p>One of the most common uses for LINQ is to filter data using the <code>Where<\/code> method. The <code><strong>Where<\/strong><\/code> method takes a lambda expression which is capable of performing almost any number of filtering operations by using multiple logical operators [<code>&amp;&amp; ||<\/code>].<\/p>\n<p>The following example shows a query requiring that five criteria are met to yield results. The query is more self-obfuscating than self-explanatory, especially without knowing any of the context that the original developer may have had when it was created. If we were asked to modify the query to meet a new business requirement, we could certainly figure out the details given enough time. If the original developer had used a better approach from the beginning, we&#8217;d now have an easier task.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tvar posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(post =&gt; post.IsPublished &amp;&amp; post.PostedOn &lt;= today &amp;&amp;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (post.PostedOn &gt;= cutoffDate || post.Author == featuredAuthor &amp;&amp; post.PostedOn &gt;= featuredAuthorCutoffDate));\n\t\t\u00a0\n<\/pre>\n<p class=\"caption\">Using multiple operators can create complex queries.<\/p>\n<p>Now that we have seen where we can improve, we&#8217;ll discuss the Pipe and Filter pattern and how we can apply it using LINQ.<\/p>\n<h2>Pipe and Filter pattern<\/h2>\n<p>The <strong>pipe and filter pattern<\/strong> in its simplest form can be defined as &#8220;A chain of multiple operations used to get specific results.&#8221; The pipes and filters pattern is a common programming design pattern with many uses. <a href=\"http:\/\/en.wikipedia.org\/wiki\/Pipeline_(software)\">http:\/\/en.wikipedia.org\/wiki\/Pipeline_(software)<\/a><\/p>\n<p>The pattern name comes from the idea of filtering water from a source as its being piped to a faucet. In the context of this article we will be taking data from a source <em>[database]<\/em> and chaining together multiple operations to get a usable subset of the data for another layer in our application.<\/p>\n<p>To construct our filters we will be using <code>IQueryable<\/code> and the LINQ <code>Where<\/code> method, as we learn more about the API we&#8217;ll build smaller filter components or <strong>&#8220;rules&#8221;<\/strong> which will allow for greater readability, reusability, and flexibility.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1899-Pipes-and-filters-630x235.jpg\" alt=\"1899-Pipes-and-filters-630x235.jpg\" width=\"630\" height=\"235\" \/><\/figure>\n<p class=\"illustration\">\u00a0<\/p>\n<h2>Understanding IQueryable and Where<\/h2>\n<p>Before we begin writing filters let&#8217;s see how the LINQ API handles method chaining and how it acts when multiple <code>Where<\/code> methods are called.<\/p>\n<p>The <code>Where<\/code> method extends <code>IQueryable<\/code><code>&lt;T&gt;<\/code> in just the same way as most LINQ methods. This allows us to call <code>Where<\/code> from other LINQ methods and collections that implement the <code>IQueryable<\/code><code>&lt;T&gt;<\/code> interface. <code>Where<\/code> also returns <code>IQueryable<\/code><code>&lt;T&gt;<\/code>, thereby allowing additional methods to be called on the results. The <code>Whe<\/code><code>re<\/code> method also takes a parameter named, <strong>predicate<\/strong>.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1899-IQueryable-Extensions-630x307.jpg\" alt=\"1899-IQueryable-Extensions-630x307.jpg\" width=\"630\" height=\"307\" \/><\/figure>\n<p class=\"illustration\">\u00a0<\/p>\n<p><code>IQueryable<\/code> does not store the results of a query but instead stores the commands required to build a query. These commands will result in an <strong>e<\/strong><strong>xpression <\/strong><strong>t<\/strong><strong>ree<\/strong>. We will look deeper into expression trees later when we take an in depth look at the predicate parameter of the <code>Where<\/code> method, but for now we&#8217;ll focus on extending <code>IQueryable<\/code> since this is a relatively simple task.<\/p>\n<p>When multiple <code>Where<\/code> methods are chained together, the result is the equivalent of using the <code>AndAlso<\/code> [<code>&amp;&amp;<\/code>] operator. This means we can use the following code interchangeably.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tvar query = query.Where(x =&gt; x.Value ==  1 &amp;&amp;\n\t\t\u00a0x.Name == name);\n\t\t\u00a0\n\t\t\/\/ equivelent to\n\t\tvar query = query.Where(x =&gt; x.Value ==  1)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(x =&gt; x.Name == name);\n<\/pre>\n<p>The first statement is more concise, yet the second offers more flexibility. Both will result in the same query.<\/p>\n<h2>Writing a custom filter<\/h2>\n<p>We can now begin writing custom filters, using what we learned about <code>IQueryable<\/code> and the <code>Where<\/code> method. By creating an extension method that both extends and returns <code>IQueryable<\/code><code>&lt;T&gt;<\/code> we can create our own chainable filter method.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tpublic  static IQueryable&lt;T&gt; MyFilter(this IQueryable&lt;T&gt; query)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/do something\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return query; \n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n<\/pre>\n<p class=\"caption\">An example filter extension method<\/p>\n<p>Let&#8217;s look at an expanded version of our example of rather unintelligible LINQ code. We&#8217;ll now refactor two methods that return a set of blog posts from a repository.<\/p>\n<p>The first method <code>GetArticles<\/code> is a filtered set of data which is further reduced by the <code>S<\/code><code>kip<\/code> and <code>T<\/code><code>ake<\/code> methods to facilitate paging. The second method <code>GetFeaturedArticles<\/code> returns several filters with multiple rules. The filters and rules combine to define a <strong>&#8220;featured article&#8221;<\/strong>, however there is very little context telling us how this is accomplished.<\/p>\n<pre class=\"lang:c# theme:vs2012\">public IEnumerable&lt;Post&gt; GetArticles(DateTime today, int pageIndex, int itemsPerPage)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(post =&gt; post.IsPublished &amp;&amp;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 post.PostedOn &lt;= today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Skip(pageIndex)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Take(itemsPerPage);\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\tpublic IEnumerable&lt;Post&gt; GetFeaturedArticles(DateTime today, DateTime cutoffDate, string featuredAuthor, DateTime featuredAuthorCutoffDate)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(post =&gt; post.IsPublished &amp;&amp; post.PostedOn &lt;= today &amp;&amp;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 (post.PostedOn &gt;= cutoffDate || post.Author == featuredAuthor &amp;&amp; post.PostedOn &gt;= featuredAuthorCutoffDate));\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n<\/pre>\n<p>Let&#8217;s apply what we have learned so far and refactor the two methods using the pipe and filter pattern.<\/p>\n<p>In the <code>GetArticles<\/code> method we can see there are two conditions that must be met: only posts that are published and only those that have a <code>PostedOn<\/code> date less than or equal to <code>today<\/code>. Since the two conditions are joined using the <code>AndAlso<\/code> [<code>&amp;&amp;<\/code>] operator, they can be rewritten as separate <code>Where<\/code> statements. The code below shows how one could rewrite the filter statements, and it includes a comment to explain their function.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\t\/\/ Before\n\t\t.Where(post =&gt; post.IsPublished &amp;&amp; \n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 post.PostedOn &lt;= today)\n\t\t\u00a0\n\t\t\/\/ After\n\t\t.Where(post =&gt; post.IsPublished)  \/\/Are published\n\t\t.Where(post =&gt; post.PostedOn &lt;= today)  \/\/Posted on or before today\n<\/pre>\n<p>Now that we have separated the statements, we&#8217;ll write extension method filters that are as easy to read as the comments <em>&#8220;Are published&#8221;<\/em> and <em>&#8220;Posted on or before today&#8221;.<\/em><\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tpublic  static  class PostFilters\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0  public  static IQueryable&lt;Post&gt; ArePublished(this IQueryable&lt;Post&gt; posts)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return posts.Where(post =&gt; post.IsPublished);\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0  public  static IQueryable&lt;Post&gt; PostedOnOrBefore(this IQueryable&lt;Post&gt; posts, DateTime today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return posts.Where(post =&gt; post.PostedOn &lt;= today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t}\n<\/pre>\n<p>Since our extension methods follow the LINQ API pattern of extending <code>IQueryable<\/code> and returning <code>IQueryable<\/code>, we can completely replace the <code>W<\/code><code>here<\/code> statements with our custom filters.<\/p>\n<pre class=\"lang:c# theme:vs2012\">public IEnumerable&lt;Post&gt; GetArticles(DateTime today, int pageIndex, int itemsPerPage)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .ArePublished()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .PostedOnOrBefore(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Skip(pageIndex)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Take(itemsPerPage);\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0 \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0public IEnumerable&lt;Post&gt; GetFeaturedArticles(DateTime today, DateTime cutoffDate, string featuredAuthor, DateTime featuredAuthorCutoffDate)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .ArePublished()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .PostedOnOrBefore(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(post =&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 post.PostedOn &gt;= cutoffDate ||\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 post.Author == featuredAuthor &amp;&amp; post.PostedOn &gt;= featuredAuthorCutoffDate);\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n<\/pre>\n<p>By using this simple pattern our code reads more like human language instead of a set of conditions.<\/p>\n<p>Extension methods are easy and require very little code to implement. However, they work in limited contexts where rules can be combined using the <code>AndAlso<\/code> [<code>&amp;&amp;<\/code>] operator. If we continue using extension methods with the example code, we could encapsulate the remaining <code>Where<\/code> method. The effect of doing this would be less than ideal because the resulting extension method would require several parameters and therefore wouldn&#8217;t be likely to improve readability.<\/p>\n<p>To further improve upon our pipes and filters pattern, we&#8217;ll need to learn more about the <code>Where<\/code> method and the <code>predicate<\/code> parameter.<\/p>\n<h2>Predicates, Expressions and Expression Trees<\/h2>\n<p>Previously, we looked at the <code>Where<\/code> method and how it extends and returns <code>IQueryable<\/code>. Using this convention, we were able to create an extension method filter that is easily readable and has a single responsibility.<\/p>\n<p>The code now requires some additional work due to limiting factors of the <code>Where<\/code> method. Let&#8217;s examine the <code>Where<\/code> method again and use this information to expand upon our filter pattern. This time we&#8217;ll focus on the <code>predicate<\/code> parameter and learn to apply <strong>rules<\/strong> for filtering our data.<\/p>\n<p>If we look at the <code>Where<\/code> method signature, we&#8217;ll see that it takes an <code>Expression&lt;<\/code><code>Func<\/code><code>&lt;<\/code><code>TSource<\/code><code>, <\/code><code>bool<\/code><code>&gt;&gt;<\/code> parameter named <code>predicate<\/code>. A predicate in C# is usually defined as <strong>&#8220;A function that returns a Boolean result&#8221;<\/strong>, but in this case there is more taking place. The type is actually an <code>Expression&lt;T&gt;<\/code> where T is the predicate, this means that we aren&#8217;t actually supplying a function but rather an expression of that function. The inner portion of the type <code>Func<\/code><code>&lt;<\/code><code>TSource<\/code><code>, <\/code><code>bool<\/code><code>&gt;<\/code> tells us that the expression of our function takes a generic type <code>TSource<\/code> and returns type is a Boolean value.<\/p>\n<p>It&#8217;s important to understand the differences between the expression of a function and a function delegate; <code>Expression&lt;<\/code><code>Func<\/code><code>&lt;<\/code><code>TSource<\/code><code>, <\/code><code>bool<\/code><code>&gt;&gt;<\/code> and <code>Func<\/code><code>&lt;<\/code><code>TSource<\/code><code>, <\/code><code>bool<\/code><code>&gt;<\/code>. An expression of a function is a complex set of Expression object types that form an expression tree. The expression tree contains parameters, operators, constants and other meta-data that can be created, examined, and manipulated with code during runtime.<\/p>\n<figure><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1899-Expression-tree-diagram-630x515.jpg\" alt=\"1899-Expression-tree-diagram-630x515.jpg\" width=\"630\" height=\"515\" \/><\/figure>\n<p class=\"illustration\">\u00a0<\/p>\n<h3>Creating Expression Trees<\/h3>\n<p>Expressions do not have constructors, there is no way to &#8220;new up&#8221; an Expression.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tvar myExpression =  new Expression()  \/\/ Invalid syntax\n<\/pre>\n<p>We could use the Expression API factory methods to create an expression tree. There are many expression factory methods that we would need to invoke in order to create a single expression tree. Each parameter, constant and operator in a single expression requires its own Expression object, each are then combine using the Expression API to form the final expression tree. These manual methods are very verbose and take significant effort to construct.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\t\/\/ Manually build the expression tree for\u00a0  \n\t\t\/\/ the lambda expression num =&gt; num &lt; 5.\n\t\tParameterExpression numParam = Expression.Parameter(typeof(int),  \"num\");\n\t\tConstantExpression five = Expression.Constant(5,  typeof(int));\n\t\tBinaryExpression numLessThanFive = Expression.LessThan(numParam, five);\n\t\tExpression&lt;Func&lt;int,  bool&gt;&gt; lambda1 =\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 Expression.Lambda&lt;Func&lt;int,  bool&gt;&gt;(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 numLessThanFive,\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  new ParameterExpression[] { numParam });\n<\/pre>\n<p><a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb397951.aspx\">http:\/\/msdn.microsoft.com\/en-us\/library\/bb397951.aspx<\/a><\/p>\n<p>Alternatively we can use the compiler to do a majority of the work for us by assigning a lambda expression to an <code>Expression&lt;T&gt;<\/code>. In fact, we&#8217;re already using this syntax with the LINQ API inside the <code>Where<\/code> parameter.<\/p>\n<pre>Expression&lt;Func&lt;int, bool&gt;&gt; lambda = num =&gt; num &lt; 5;<\/pre>\n<p class=\"caption\">Creating a lambda expression tree using the compiler.<\/p>\n<p>Both approaches have their benefits; while the lambda syntax is much easier to write and quicker to understand, the manual method can be manipulated at runtime. We&#8217;ll use these strengths and weakness to our advantage when building expressions [rules] for our filters.<\/p>\n<h3>Working with Expression Trees<\/h3>\n<p>Let&#8217;s consider how we might work with expression trees in our example problem. If we could replace each condition in the <code>Where<\/code> method with a function that returns an Expression we could clean up the statement much like we did using extension method filters.<\/p>\n<p>Continuing with the blog posts example, let&#8217;s look at the first condition <code>(<\/code><code>post.PostedOn<\/code><code> &gt;= <\/code><code>cutoffDate<\/code><code>)<\/code>, we can see that the post is being checked to see if it was posted on or after the cutoff date. It would clean up our code nicely if we could create a <code>PostedOnOrAfter<\/code> function to replace the condition. If we continue with the other conditions, it might look something like the example below.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/ Before\n\t...\n\t\u00a0 .Where(post =&gt;\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 post.PostedOn &gt;= cutoffDate ||\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 post.Author == featuredAuthor &amp;&amp; post.PostedOn &gt;= featuredAuthorCutoffDate);\n\t...\n\t\u00a0\n\t\/\/ After\n\t\/\/ Note: Will not compile\n\t...\n\t.Where(PostedOnOrAfter(cutoffDate) ||\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WithFeaturedAuthor(featuredAuthor) &amp;&amp;\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 PostedOnOrAfter(featuredAuthorCutoffDate);\n\t...\n\t\u00a0\n\tprivate Expression&lt;Func&lt;Post,bool&gt;&gt; PostedOnOrAfter(DateTime cutoffDate)\n\t{\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 return post =&gt; post.PostedOn &gt;= cutoffDate; \n\t};\n\tprivate Expression&lt;Func&lt;Post, bool&gt;&gt; WithFeaturedAuthor(string featuredAuthorName)\n\t{\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 return post =&gt; post.Author == featuredAuthorName;\n\t}\n<\/pre>\n<p>Unfortunately this code <strong>will not compile<\/strong> because Expressions cannot be combined using the <code>&amp;&amp;<\/code> and <code>||<\/code> operators.<\/p>\n<p>Since we have accomplished as much as we can using the lambda syntax we will need to exploit the Expression API. Using the Expression API we can create a utility that will take apart and reassemble multiple Expressions into a single valid Expression.<\/p>\n<p>We will use extension methods again to make the syntax fluent and easy to read and write. This time we&#8217;ll create <code>And<\/code> and <code>Or<\/code> extension methods, that will serve as an API for calling our utility. The method, <code>CombineLambdas<\/code> is responsible for working with the Expression API. An <code>ExpressionVisitor<\/code>, a special class used to traverse expression trees, will be used to rewrite the expressions <code>TSource<\/code> parameter at runtime. If the parameters are not of the same instance, then an &#8220;out of scope&#8221; error will occur at runtime.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tpublic  static  class PredicateExtensions\n\t\t\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/  &lt;summary&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/ Begin an expression chain\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/  &lt;\/summary&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/  &lt;typeparam id=\"T\"\"&gt;&lt;\/typeparam&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/  &lt;param id=\"value\"\"&gt;Default return value if the chanin is ended early&lt;\/param&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/\/  &lt;returns&gt;A lambda expression stub&lt;\/returns&gt;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  public  static Expression&lt;Func&lt;T,  bool&gt;&gt; Begin&lt;T&gt;(bool value =  false)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  if (value)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return parameter =&gt;  true;  \/\/value cannot be used in place of true\/false\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return parameter =&gt;  false;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  public  static Expression&lt;Func&lt;T,  bool&gt;&gt; And&lt;T&gt;(this Expression&lt;Func&lt;T,  bool&gt;&gt; left,\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Expression&lt;Func&lt;T,  bool&gt;&gt; right)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return CombineLambdas(left, right, ExpressionType.AndAlso);\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  public  static Expression&lt;Func&lt;T,  bool&gt;&gt; Or&lt;T&gt;(this Expression&lt;Func&lt;T,  bool&gt;&gt; left, Expression&lt;Func&lt;T,  bool&gt;&gt; right)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return CombineLambdas(left, right, ExpressionType.OrElse);\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  #region private\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  private  static Expression&lt;Func&lt;T,  bool&gt;&gt; CombineLambdas&lt;T&gt;(this Expression&lt;Func&lt;T,  bool&gt;&gt; left,\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Expression&lt;Func&lt;T,  bool&gt;&gt; right, ExpressionType expressionType)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  \/\/Remove expressions created with Begin&lt;T&gt;()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  if (IsExpressionBodyConstant(left))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return (right);\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ParameterExpression p = left.Parameters[0];\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 SubstituteParameterVisitor visitor =  new SubstituteParameterVisitor();\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 visitor.Sub[right.Parameters[0]] = p;\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Expression body = Expression.MakeBinary(expressionType, left.Body, visitor.Visit(right.Body));\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return Expression.Lambda&lt;Func&lt;T,  bool&gt;&gt;(body, p);\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0 \n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  private  static  bool IsExpressionBodyConstant&lt;T&gt;(Expression&lt;Func&lt;T,  bool&gt;&gt; left)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return left.Body.NodeType == ExpressionType.Constant;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  internal  class SubstituteParameterVisitor : ExpressionVisitor\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  public Dictionary&lt;Expression, Expression&gt; Sub =  new Dictionary&lt;Expression, Expression&gt;();\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  protected  override Expression VisitParameter(ParameterExpression node)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 Expression newValue;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  if (Sub.TryGetValue(node,  out newValue))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return newValue;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  return node;\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0  #endregion\n\t\t\u00a0\u00a0\u00a0 }<\/pre>\n<p class=\"caption\">The utility code combines nodes of two expression trees and returns a single lambda expression.<\/p>\n<p>With our utility in place, we can finish refactoring. <code>Where<\/code> previously we tried using operators before to combine expressions, we will now simply chain them together using <code>And<\/code> and <code>Or<\/code>. Now we have rules that read like spoken language, and we can clearly comprehend the code&#8217;s intent.<\/p>\n<pre class=\"lang:c# theme:vs2012\">...\n\t\t.Where(PostedOnOrAfter(cutoffDate).Or(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WithFeaturedAuthor(featuredAuthor).And(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 PostedOnOrAfter(featuredAuthorCutoffDate))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ));\n\t\t...\n\t\t\u00a0\n\t\tprivate Expression&lt;Func&lt;Post,bool&gt;&gt; PostedOnOrAfter(DateTime cutoffDate)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 return post =&gt; post.PostedOn &gt;= cutoffDate;\n\t\t};\n\t\t\u00a0\n\t\tprivate Expression&lt;Func&lt;Post, bool&gt;&gt; WithFeaturedAuthor(string featuredAuthorName)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 return post =&gt; post.Author == featuredAuthorName;\n\t\t};\n<\/pre>\n<h2>Putting it together<\/h2>\n<p>Now that we have created filters using extension methods and rules using expression trees, let&#8217;s give our example code one last refactor. We&#8217;ll take a last pass through the code making it as concise as possible.<\/p>\n<pre class=\"lang:c# theme:vs2012\">public IEnumerable&lt;Post&gt; GetArticles(DateTime today, int pageIndex, int itemsPerPage)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .ArePublished()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .PostedOnOrBefore(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Skip(pageIndex)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Take(itemsPerPage);\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t}\n\t\t\u00a0\n\t\tpublic IEnumerable&lt;Post&gt; GetFeaturedArticles(DateTime today, DateTime cutoffDate, string featuredAuthor, DateTime featuredAuthorCutoffDate)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 var posts = postRepository.GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .ArePublished()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .PostedOnOrBefore(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(PostedOnOrAfter(cutoffDate).Or(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WithFeaturedAuthor(featuredAuthor).And(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 PostedOnOrAfter(featuredAuthorCutoffDate))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ));\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t}\u00a0\u00a0 \n<\/pre>\n<p>The example in its current state can still be refactored.<\/p>\n<p>The <code>GetArticles<\/code> and <code>GetFeaturedArticles<\/code> methods both begin with the same set of filters. These common filters can be included within a single function along with the call to the repository; it will serve as a starting point for further filtering. This method can be considered a <strong>pipe<\/strong> in our design pattern because it is taking data from the source and delivering it to the next operation. We won&#8217;t need an extension method here because the method will not be called from inside the method chain.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\/\/pipe\n\t\tpublic IQueryable&lt;Post&gt; GetVisiblePosts (DateTime today)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return postRepository\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .GetAll()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .ArePublished()\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .PostedOnOrBefore(today);\n\t\t}\n\t\tpublic IEnumerable&lt;Post&gt; GetArticles(DateTime today, int pageIndex, int itemsPerPage)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 GetVisiblePosts(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Skip(pageIndex)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Take(itemsPerPage);\n\t\t\u00a0\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t}\n\t\t\u00a0\n\t\tpublic IEnumerable&lt;Post&gt; GetFeaturedArticles(DateTime today, DateTime cutoffDate, string featuredAuthor, DateTime featuredAuthorCutoffDate)\n\t\t{\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 GetVisiblePosts(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(PostedOnOrAfter(cutoffDate).Or(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 WithFeaturedAuthor(featuredAuthor).And(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 PostedOnOrAfter(featuredAuthorCutoffDate))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 ));\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t}\n<\/pre>\n<p>In the <code>GetFeaturedArticles<\/code> method, the <code>Where<\/code> statements read well, but the rules could still be more specific. The second set of rules <code>WithFeaturedAuthor(featuredAuthor).And(PostedOnOrAfter(featuredAuthorCutoffDate))<\/code> are communicated more clearly as a single requirement so let&#8217;s wrap them in a single rule and reduce the statement further.<\/p>\n<pre class=\"lang:c# theme:vs2012\">...\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 GetVisiblePosts(today)\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 .Where(PostedOnOrAfter(cutoffDate).Or(\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 FeaturedAuthorPostedOnOrAfter(featuredAuthor, featuredAuthorCutoffDate))\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0 );\n\t\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 return posts;\n\t\t}\n\t\t\u00a0\n\t\tprivate Expression&lt;Func&lt;Post, bool&gt;&gt; FeaturedAuthorPostedOnOrAfter(string featuredAuthorName, DateTime featuredAuthorCutoffDate)\n\t\t{\n\t\t\u00a0  return WithFeaturedAuthor(featuredAuthorName).And(PostedOnOrAfter(featuredAuthorCutoffDate));\n<\/pre>\n<p>We&#8217;ve completely changed how the code in our example reads. We&#8217;ve taken several lambda expressions that were difficult to distinguish and transformed them into a clear human readable syntax. Each filter and rule has a single responsibility, allowing new developers to easily make modifications when requirements change.<\/p>\n<h3>Changing requirements<\/h3>\n<p>Continuing with the posts example, let&#8217;s imagine that we have been given a new requirement. In the past we have only featured a single author&#8217;s posts, the new requirement is to allow for any number of &#8220;featured authors&#8221; to be displayed. The featured authors&#8217; names are provided as a string array which will be used in the query for featured authors.<\/p>\n<p>Using traditional lambda expressions wouldn&#8217;t work for this requirement since we have an unknown number of featured authors. We will have to iterate through the array and dynamically build the query by appending multiple <code>Or<\/code> statements. Because we have separated our rules into single operations and have the ability to chain them using our expression utility, the task will be trivial.<\/p>\n<p>Instead of modifying the <code>FeaturedAuthorPostedOnOrAfter<\/code> rule, we can reuse it. We will add a <code>FeaturedAuthorsPostedOnOrAfter<\/code> rule that iterates through an array and appends multiple rules using the <code>Or<\/code> extension method. To create a dynamic rule we will need a starting point to begin the method chain, for this we can use the <code>Begin<\/code> helper method of our expression utility.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\t\tvar rule = PredicateExtensions.PredicateExtensions.Begin&lt;Post&gt;();\n<\/pre>\n<p><code>Begin<\/code> creates a <code>parameter =&gt; false<\/code> Expression, a valid rule that is discarded once the first rule is appended via <code>And<\/code> or <code>Or<\/code>, if no rules are appended the Expression will execute with our error.<\/p>\n<p>Now we can simply iterate, append and return the dynamic criteria.<\/p>\n<pre class=\"lang:c# theme:vs2012\">\tprivate Expression&lt;Func&lt;Post, bool&gt;&gt; FeaturedAuthorsPostedOnOrAfter(string[] featuredAuthorNames, DateTime featuredAuthorCutoffDate)\n\t{\n\tvar rule = PredicateExtensions.PredicateExtensions.Begin&lt;Post&gt;();\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 foreach (var authorName in featuredAuthorNames)\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 {\n\t\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 rule = rule.Or(FeaturedAuthorPostedOnOrAfter(authorName, featuredAuthorCutoffDate));\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 }\n\t\u00a0\u00a0\u00a0\u00a0\u00a0 return rule;\n\t}\n<\/pre>\n<h2>Conclusion<\/h2>\n<p>In this article we took a deep dive into <code>IQueryable<\/code>, <code>Where<\/code> and <code>Expression<\/code><code>.<\/code> By using what we learned, we were able to implement the pipe and filter design pattern and add rules for filtering data. We started with simple <code>IQueryable<\/code> extension methods to create filters that improved the readability of our code. We explored expression trees and saw how to manipulate them. Using an Expression utility we created a flexible API for writing rules, in addition we gained the ability to create dynamic data queries at runtime.<\/p>\n<p>Using the ideas from the examples given here should be considered on a per-project basis. Some of the techniques may work better in certain circumstances than in others. Experiment with pipes, filters and rules to see which combination works right for the task at hand.<\/p>\n<h2>Links<\/h2>\n<p>The sample project for this article can be found on GitHub.<br \/><a href=\"https:\/\/github.com\/EdCharbeneau\/PredicateExtensions\">https:\/\/github.com\/EdCharbeneau\/PredicateExtensions<\/a><\/p>\n<p>The PredictateExtensions binary<br \/>[<a href=\"http:\/\/www.nuget.org\/packages\/PredicateExtensions\/\">http:\/\/www.nuget.org\/packages\/PredicateExtensions\/<\/a>]<br \/>&#8230; and source &#8230;<br \/>[<a href=\"http:\/\/www.nuget.org\/packages\/PredicateExtensions.Source\/\">http:\/\/www.nuget.org\/packages\/PredicateExtensions.Source\/<\/a>]<br \/>&#8230; are also available on NuGet. (This is not production software and should be used merely as a starting point for your own projects or exploration.)<\/p>\n<\/div>\n<p>\u00a0<\/p>\n<p>\u00a0<\/p>\n\n\n\n<section id=\"faq\" class=\"faq-block my-5xl\">\n    <h2>FAQs:Giving Clarity to LINQ Queries by Extending Expressions<\/h2>\n\n                        <h3 class=\"mt-4xl\">1. What are LINQ expression trees in C#?<\/h3>\n            <div class=\"faq-answer\">\n                <p>An expression tree is a data structure that represents code as a tree of objects &#8211; rather than compiled IL, each expression (comparison, method call, lambda body) is an in-memory tree node. LINQ&#8217;s IQueryable uses expression trees to pass query logic to providers (Entity Framework, LINQ to SQL) which translate the tree into SQL. Expression trees allow you to inspect, modify, and compose query logic at runtime &#8211; for example, combining multiple predicate expressions with Expression.AndAlso into a single Where clause, or building dynamic queries from user-provided search criteria.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">2. How do I extend IQueryable with custom filter methods in C#?<\/h3>\n            <div class=\"faq-answer\">\n                <p>Create a static class with extension methods that accept and return IQueryable&lt;T&gt;: public static IQueryable&lt;Post&gt; PublishedByAuthor(this IQueryable&lt;Post&gt; query, string author) =&gt; query.Where(p =&gt; p.IsPublished &amp;&amp; p.Author == author); Chain these in your queries: var results = dbContext.Posts.PublishedByAuthor(&#8220;Ed&#8221;).CreatedAfter(lastMonth).ToList(); Each method adds a Where clause to the expression tree &#8211; EF Core sees the combined tree and translates it into a single SQL query with all conditions in the WHERE clause.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">3. How do I combine LINQ predicate expressions in C#?<\/h3>\n            <div class=\"faq-answer\">\n                <p>Use Expression.AndAlso(expr1, expr2) to combine two Expression&lt;Func&lt;T, bool&gt;&gt; predicates with logical AND, or Expression.OrElse for OR. The expressions must share the same parameter &#8211; rebind them using an ExpressionVisitor or a helper like the PredicateBuilder from LinqKit. Once combined, invoke the composed expression with .Where(combinedExpression). This is particularly useful for building dynamic search filters where the combination of conditions varies at runtime based on user input.<\/p>\n            <\/div>\n                    <h3 class=\"mt-4xl\">4. What is the Pipe and Filter pattern in LINQ?<\/h3>\n            <div class=\"faq-answer\">\n                <p>The Pipe and Filter pattern structures data transformation as a sequence of independent filter operations &#8211; each filter takes data in and passes a narrowed or transformed result to the next. In LINQ, this maps naturally to chained IQueryable extension methods where each method adds one condition or transformation. The benefit: each filter is a named, testable, single-responsibility operation; combining them reads as an English description of the query&#8217;s intent. Contrast with a single Where clause containing a complex lambda expression &#8211; readable today, opaque to the next developer (or your future self).<\/p>\n            <\/div>\n            <\/section>\n","protected":false},"excerpt":{"rendered":"<p>Build composable, reusable LINQ query filters in C# using IQueryable extension methods, expression trees, and the Pipe and Filter pattern. Covers Expression.AndAlso\/OrElse composition and combining predicates cleanly with Entity Framework.&hellip;<\/p>\n","protected":false},"author":58772,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":true,"footnotes":""},"categories":[143538],"tags":[4143,4229,4706],"coauthors":[6808],"class_list":["post-1725","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","tag-net","tag-net-framework","tag-linq"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1725","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/58772"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=1725"}],"version-history":[{"count":9,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1725\/revisions"}],"predecessor-version":[{"id":109779,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1725\/revisions\/109779"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=1725"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=1725"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=1725"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=1725"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}