title: How can I pass a Predicate<T> to the Where() method in Linq to SQL?
body: <p>I have the following model:</p>
  
  <pre><code> +--------+
   | Folder |
   +--------+
       | 1
       |
       | *
  +----------+         +---------+
  | WorkItem |---------| Project |
  +----------+ *     1 +---------+
  </code></pre>
  
  <p>I need to retrieve a list of Folders with the current count of WorkItems.</p>
  
  <p>If I have specified a Project, then I only want the count of WorkItems in each Folder that are associated with the specified Project.</p>
  
  <p>If no Project is specified, it should return the total WorkItem count.</p>
  
  <p>I have the following Linq to SQL code:</p>
  
  <pre><code>public interface IWorkItemCriteria {
      int? ProjectId { get; }
  }
  
  public static IQueryable&lt;Folder&gt; GetFoldersWithItemCounts(IWorkItemCriteria criteria) {
      var results = from folder in dataContext.Folders
          select new {
                Folder = folder,
                Count = folder.WorkItems.Count()
      };
      return(results);
  }
  </code></pre>
  
  <p>The problem is - I want to filter the work items that are being counted.</p>
  
  <p>This works:</p>
  
  <pre><code>    var results = from folder in dataContext.Folders
          select new {
                Folder = folder,
                Count = folder.WorkItems.Where(item =&gt; item.ProjectId == criteria.ProjectId).Count()
      };
  </code></pre>
  
  <p>but I can't get it to use any kind of dynamic predicate / expression. The syntax I'm trying to use is:</p>
  
  <pre><code>    var results = from folder in dataContext.Folders
          select new {
                Folder = folder,
                Count = folder.WorkItems.Where(filter).Count()
      };
  </code></pre>
  
  <p>I've tried</p>
  
  <pre><code>Predicate&lt;WorkItem&gt; filter = (item =&gt; item.ProjectId == criteria.ProjectId);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>Expression&lt;Func&lt;WorkItem, bool&gt;&gt; filter = (item =&gt; item.ProjectId == criteria.ProjectId)
  </code></pre>
  
  <p>neither of which will compile - gives <code>The type arguments for method 'System.Linq.Enumerable.Where&lt;TSource&gt; (System.Collections.Generic.IEnumerable&lt;TSource&gt;, System.Func&lt;TSource,bool&gt;)' cannot be inferred from the usage. Try specifying the type arguments explicitly.</code></p>
  
  <p>I've tried</p>
  
  <pre><code>Func&lt;WorkItem, bool&gt; filter = (item =&gt; item.ProjectId == criteria.ProjectId);
  </code></pre>
  
  <p>which builds, but then fails with 'Unsupported overload used for query operator 'Where'.'</p>
  
  <p>I'm going to need to add additional properties to the IWorkItemCriteria interface, so the ability to dynamically construct a predicate that can be cleanly translated by Linq to SQL is pretty important.</p>
  
  <p>Any ideas?</p>