title: Is there a way I can cache a LINQ parameter and reuse it later?
body: <p>Is there a way I can cache a LINQ parameter and reuse it later for optimization?</p>
  <p>Here is my situation.</p>
  <pre><code>public interface IEmployee
  {
      ProjectCollection GetProjects();
      // ...
  }
  
  public class ProjectCollection
  {
      List&lt;Project&gt; EmployeeProjects { get; private set; }
      // ...
  }
  
  public class Project
  {
      public Guid ProjectId { get; private set; }
      // ...
  }
  </code></pre>
  <p>Now given a list of employees List, and a given ProjectId (guid), I need to retrieve the Project object.</p>
  <p>I've tried a combination of two LINQ statements, one to find the right employee, and one to find the right project. <strong>But is there a way to do it in one statement, or at least optimize it by caching the employee somewhere?</strong></p>
  <pre><code>public Project GetProject(List&lt;IEmployee&gt; employees, Guid id)
  {
      Project rtn = null;
  
      // Step 1: Retrieve the employee who has the right project.
      var employeeWithProject = employees.Where (e =&gt; e.GetProjects().EmployeeProjects.Any(p =&gt; p.ProjectId.Equals(guid))).FirstOrDefault(); // Note: This retrieves the employee. But I need to cache the part [e.GetProjects().EmployeeProjects] to query it later.
  
      if employeeWithProject != null)
      {
          // Step 2: Retrieve the project itself.
          rtn = employeeWithProject.GetProjects().EmployeeProjects.Where(p =&gt; p.ProjectId.Equals(guid)).FirstOrDefault(); // Note: This retrieves the actual project from the previously set employeeWithProject
      }
  
      return rtn; // nothing found
  }
  </code></pre>
  <p>I really don't like this solution, and was wondering if anyone could help me optimize it. It basically iterates through the Projectcollection twice. So if anyone can think of a way to do the whole thing with a single LINQ statement I'd appreciate it.</p>
  <p>Thanks.</p>