Note that there are some explanatory texts on larger screens.

plurals
  1. POC# and LINQ: ordering a query by a nested query's value
    primarykey
    data
    text
    <p>I'm writing a simple forum in ASP.NET that sits on top of an Entity Framework database in C#.</p> <p>Each <code>Topic</code> object has a navigation property <code>Posts</code> pointing to a collection of <code>Post</code> objects. Each <code>Post</code> object has a property <code>When</code> that indicates when the post was made.</p> <p><code>Post.Parent</code> is type <code>Topic</code>. <code>Post.Identifier</code> and <code>Topic.Identifier</code> is type <code>Int32</code>. Only <code>Post</code> has a <code>When</code> property; <code>Topic</code> has no such property. <code>Topic.Parent</code> is a third type <code>Forum</code> that is referenced by its <code>Identifier</code>.</p> <p>My problem is this: I can't seem to find a way to sort all Topic objects by the <em>last</em> post made in each topic. I've tried this:</p> <pre class="lang-cs prettyprint-override"><code>var topics = from t in context.Topics from p in a.Posts where t.Parent.Identifier == forum.Identifier orderby p.When descending select t; </code></pre> <p>But I got duplicate <code>Topic</code> objects and sorting was <em>not</em> by latest post date descending. </p> <p>I then tried this:</p> <pre class="lang-cs prettyprint-override"><code>var topics = (from t in context.Topics let lastPost = (from p in context.Posts where p.Parent.Identifier == a.Identifier orderby p.When descending select p).FirstOrDefault().When where t.Parent.Identifier == forum.Identifier orderby lastPost descending select t).Distinct(); </code></pre> <p>It eliminated the duplicate problem, but still no sorting. I even tried <a href="https://stackoverflow.com/questions/931617/linq-query-for-a-forum">a suggestion from another question</a>:</p> <pre class="lang-cs prettyprint-override"><code>var topics = (from t in context.Topics let posts = context.Posts.Where(p =&gt; p.Parent.Identifier == t.Identifier) let lastPost = posts.OrderByDescending(p =&gt; p.When).FirstOrDefault() where t.Parent.Identifier == forum.Identifier orderby lastPost.When descending select t); </code></pre> <p>Not sure what to try next; it seems that these more advanced LINQ expressions escape me. Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload