title: Conditionally call Linq extension method
body: <p>I have an abstract class that implement all of my queries. My Get function is:</p>
  
  <pre><code>public virtual List&lt;TEntity&gt; Get(Expression&lt;Func&lt;TEntity, bool&gt;&gt; criteria)
  {
      return _dbSet.Where(criteria).OrderByDescending(OrderBy).ThenBy(ThenOrderBy).ToList();
  }
  </code></pre>
  
  <p>And the ThenOrderBy property is:</p>
  
  <pre><code>public virtual Func&lt;TEntity, object&gt; ThenOrderBy { get; set; }
  </code></pre>
  
  <p>The <strong>OrderBy</strong> property is required, but my new property, <strong>ThenOrderBy</strong> is not required and not implemented in all classes that inherits this abstract class.</p>
  
  <p>I am getting this error:</p>
  
  <blockquote>
    <p>Value can not be null</p>
  </blockquote>
  
  <p>Is there any way to mantain this clean code without putting blocks of "if's" statments?</p>
  
  <p><strong>Solution that I Used:</strong></p>
  
  <pre><code>public virtual List&lt;TEntity&gt; Consultar(Expression&lt;Func&lt;TEntity, bool&gt;&gt; criteria)
  {
      var query = _dbSet.Where(criteria);
      query = OrderDescending ?
              query.OrderByDescending(OrderBy).AndOptionallyBy(ThenOrderBy) 
              : 
              query.OrderBy(OrderBy).AndOptionallyBy(ThenOrderBy);
      query = (paggedSearch &amp;&amp; Skip &gt; 0) ? query.Skip(Skip) : query;
      query = (paggedSearch &amp;&amp; Take &gt; 0) ? query.Take(Take) : query;
  
      return query.ToList();
  }
  </code></pre>
  
  <p>And Created a new Extension Class</p>
  
  <pre><code>public static class ExtensionMethods
  {
      public static IOrderedQueryable&lt;TSource&gt; AndOptionallyBy&lt;TSource, TKey&gt;(this IOrderedQueryable&lt;TSource&gt; source, Expression&lt;Func&lt;TSource, TKey&gt;&gt; keySelector)
      {
          return (keySelector == null) ? source : source.ThenBy(keySelector);
      }
  }
  </code></pre>