title: Linq: dynamic Where clause inside a nested subquery get latest records of each group
body: <p>I currently get problem to dynamic linq expression below </p>
  
  <p>My Models</p>
  
  <pre><code>public class Orders
  {
      public int OrderId ;
      public ICollection&lt;OrderStatuses&gt; Statuses;
  }  
  
  public class Statuses
  {
      public int StatusId;
      public int OrderId;
      public string Note;
      public DateTime Created;
  }
  </code></pre>
  
  <p>My Sample data : </p>
  
  <pre><code>Orders
  |  ID   | Name       |
  ----------------------
  |   1   | Order 01   |  
  |   2   | Order 02   | 
  |   3   | Order 03   | 
  
  Statuses
  |ID | OrderId | Note      | Created   |
  ---------------------------------------
  | 1 |  1      | Ordered   | 2016-03-01|
  | 2 |  1      | Pending   | 2016-04-02|
  | 3 |  1      | Completed | 2016-05-19|
  | 4 |  1      | Ordered   | 2015-05-19|
  | 5 |  2      | Ordered   | 2016-05-20|
  | 6 |  2      | Completed | 2016-05-19|
  | 7 |  3      | Completed | 2016-05-19|
  </code></pre>
  
  <p>I'd like to get number of orders which have note value equal to <strong>'Ordered'</strong> and <strong>max created time</strong>.
  Below is sample number of orders that I expect from query</p>
  
  <pre><code>| Name     |  Note    |  Last Created|
  -------------------------------------|
  | Order 01 |  Ordered | 2016-03-01   | 
  | Order 02 |  Ordered | 2016-05-20   |
  </code></pre>
  
  <p>Here my idea but it's seem to wrong way</p>
  
  <pre><code>var outer = PredicateBuilder.True&lt;Order&gt;();
  
  var orders   = _entities.Orders
                          .GroupBy(x =&gt; x.OrderId)
                          .Select(x =&gt; new { x.Key, Created = x.Max(g =&gt; g.Created) })
                          .ToArray();
  
  var predicateStatuses = PredicateBuilder.False&lt;Status&gt;();
  
  foreach (var item in orders)
  {
      predicateStatuses = predicateStatuses.Or(x =&gt; x.OrderId == item.Key &amp;&amp; x.Created == item.Created);
  }
  var predicateOrders = PredicateBuilder.False&lt;JobOrder&gt;();
  
  predicateOrders = predicateOrders.Or(predicateStatuses); (I don't how to passed expression which different object type (Order and Status) here or I have to write an extension method or something
  
  outer = outer.And(predicateOrders);
  </code></pre>
  
  <p>Please suggest me how to solve this dynamic linq expression in this case.
  Thanks in advance.</p>