title: LINQ: Customize the count method
body: <p>I'm trying to implement a custom LinQ <code>Count()</code> method. Basically what I'm trying to achieve here is before calling the Count method, I want to filter out all elements that have the property <code>IsDeleted</code> set to true. So, I created an extension class and I added these methods:</p>
  
  <pre><code>public static int Count2&lt;T&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, bool&gt; selector)
      where T : Model
  {
      return source.Where(x =&gt; !x.IsDeleted).Count(selector);
  }
  
  public static int Count2&lt;T&gt;(this IQueryable&lt;T&gt; source, Expression&lt;Func&lt;T, bool&gt;&gt; selector)
      where T : Model
  {
      return source.Where(x =&gt; !x.IsDeleted).Count(selector);
  }
  
  public static int Count2&lt;T&gt;(this IEnumerable&lt;T&gt; source)
      where T : Model
  {
      return source.Count(x =&gt; !x.IsDeleted);
  }
  
  public static int Count2&lt;T&gt;(this IQueryable&lt;T&gt; source)
      where T : Model
  {
      return source.Count(x =&gt; !x.IsDeleted);
  }
  </code></pre>
  
  <p>This works just find for local collections, but when executing this command for instance:</p>
  
  <pre><code>ListOfModels.Sum(x =&gt; x.PropertyThatIsAList.Count2())
  </code></pre>
  
  <p>and <code>ListOfModels</code> is an instance of <code>IQueryable</code>, i.e. it has to be executed in the database, it gives me this error:</p>
  
  <blockquote>
    <p>The LINQ expression 'Sum()' could not be translated and will be evaluated locally.</p>
  </blockquote>
  
  <p>I looked around on the web and I saw some answers saying I have to implement the <code>IQueryableProvider</code> but I think there is no need to go into such complicated path since the <code>Sum()</code> and <code>Count()</code> are translatable, I only need to count conditionally. Is it possible, and if it is, can anyone give me a clue on how to do it?</p>