title: Casting an IEnumerable<TEntity> to an IEnumerable<TResult> while ensuring deferred execution
body: <p>In my application there are a fair number of existing "service commands" which generally return a <code>List&lt;TEntity&gt;</code>. However, I wrote them in such a way that any queries would not be evaluated until the very last statement, when they are cast <code>ToList&lt;TEntity&gt;</code> (or at least I think I did).</p>
  
  <p>Now I need to start obtaining some "context-specific" information from the commands, and I am thinking about doing the following:</p>
  
  <ol>
  <li>Keep existing commands largely the same as they are today, but make sure they return an <code>IEnumerable&lt;TEntity&gt;</code> rather than an <code>IList&lt;TEntity&gt;</code>.</li>
  <li>Create new commands that call the old commands but return <code>IEnumerable&lt;TResult&gt;</code> where <code>TResult</code> is not an entity but rather a view model, result model, etc - some representation of the data that is useful for the application.</li>
  </ol>
  
  <p>The first case in which I have needed this is while doing a search for a <code>Group</code> entity. In my schema, <code>Group</code>s come with <code>User</code>-specific permissions, but it is not realistic for me to spit out the entire list of users and permissions in my result - first, because there could be many users, second, because there are many permissions, and third, because that information should not be available to insufficiently-privileged users (ie a "guest" should not be able to see what a "member" can do).</p>
  
  <p>So, I want to be able to take the result of the original command, an <code>IEnumerable&lt;Group&gt;</code>, and describe how each <code>Group</code> ought to be transformed into a <code>GroupResult</code>, given a specific input of <code>User</code> (by <code>Username</code> in this case).</p>
  
  <p>If I try to iterate over the result of the original command with <code>ForEach</code> I know this will force the execution of the result and therefore potentially result in a needlessly longer execution time. What if I wanted to further compose the result of the "new" command (that returns <code>GroupResult</code>) and filter out certain groups? Then maybe I would be calculating a ton of privileges for the inputted user, only to filter out the parent <code>GroupResult</code> objects later on anyway!</p>
  
  <p>I guess my question boils down to... how do I tell C# how I'd like to transform each member of the <code>IEnumerable</code> without necessarily doing it at the time the method is run?</p>