title: Re-use parts of a linq query
body: <p>We have a program that uses Linq-To-Sql and does a lot of similar queries on our tables.  In particular, we have a timestamp column, and we pull the most recent timestamp to see if the table has changed since our last query.</p>
  <pre><code>System.Data.Linq.Binary ts;
  ts = context.Documents
      .Select(r =&gt; r.m_Timestamp)
      .OrderByDescending(r =&gt; r)
      .FirstOrDefault();
  </code></pre>
  <p>We repeat this query often on different tables that's relevant for the current form/query whatever.  What I would like to do is create a &quot;function&quot; or something that can repeat the last 3 lines of this query (and ideally would work on every table).  Here's what I would like to write:</p>
  <pre><code>System.Data.Linq.Binary ts;
  ts = context.Documents
      .GetMostRecentTimestamp();
  </code></pre>
  <p>But I have no idea how to create this &quot;GetMostRecentTimestamp&quot;.  Also, these queries are never this simple.  They usually filter by the Customer, or by the current order, so a more valid query might be</p>
  <pre><code>ts = context.Documents
      .Where(r =&gt; r.CustomerID == ThisCustomerID)
      .GetMostRecentTiemstamp(); 
  </code></pre>
  <p>Any help?  Thanks!</p>
  <hr />
  <h3>Update [Solution]</h3>
  <p>I selected Bala R's answer, here's the code updated so it compiles:</p>
  <pre><code>public static System.Data.Linq.Binary GetMostRecentTimestamp(this IQueryable&lt;Data.Document&gt; docs)
  {
      return docs
          .Select(r =&gt; r.m_Timestamp)
          .OrderByDescending(r =&gt; r)
          .FirstOrDefault();
      }
  </code></pre>
  <p>The only drawback to this solution is that I will have to write this function for each table.   I would have loved Tejs's answer, if it actually worked, but I'm not re-designing my database for it.  Plus DateTime is a not a good way to do timestamps.</p>
  <hr />
  <h3>Update #2 (Not so fast)</h3>
  <p>While I can do a query such as Documents.Where( ... ).GetMostRecentTimestamp(), this solution fails if I try to do an association based query such as MyCustomer.Orders.GetMostRecentTimestamp(), or MyCustomer.Orders.AsQueryable().GetMostRecentTimestamp();</p>