title: Flattening Complex LINQ to SQL
body: <p>I have a somewhat complex LINQ to SQL query that I'm trying to optimise (no, not prematurely, things are slow), that goes a little bit like this;</p>
  
  <pre><code>IQueryable&lt;SearchListItem&gt; query = DbContext.EquipmentLives
      .Where(...)
      .Select(e =&gt; new SearchListItem {
          EquipmentStatusId = e.EquipmentStatuses.FirstOrDefault(s =&gt; s.DateTo == null).Id,
          StatusStartDate = e.EquipmentStatuses.FirstOrDefault(s =&gt; s.DateTo == null).DateFrom,
          ...
      });
  </code></pre>
  
  <p>The where clauses aren't important, they don't filter <code>EquipmentStatuses</code>, happy to include if someone thinks they're required.</p>
  
  <p>This is on quite a large set of tables and returns a fairly details object, there's more references to <code>EquipmentStatuses</code>, but I'm sure you get the idea. The problem is that there's quite obviously two sub-queries and I'm sure that (among some other things) is not ideal, especially since they are exactly the same sub-query each time.</p>
  
  <p>Is it possible to flatten this out a bit? Perhaps it's easier to do a few smaller queries to the database and create the <code>SearchListItem</code> in a <code>foreach</code> loop?</p>