Linq Group by and Order by
<p>I have a sql query where I group by <code>Name</code> and then order by <code>Date</code>.
I would also need to select only one entry per group with the newest Date.
How do I do that in linq (using lambda expression)?</p>

<pre><code>select Name,Date,Comment 
from Feedback
Group by Name,Date,Comment
order by Date desc
</code></pre>

<p>My linq</p>

<pre><code>var query= db.Feedback
                .GroupBy(f =&gt; f.Name, (f, g) =&gt; new
                {
                    Name = f,
                    Comment = g.Select(h =&gt; h.Comment),
                    Date= g.Select(h =&gt; h.Date)
                })
                .Select(f =&gt; new { f.Name, f.Date, f.Comment}).ToList();
</code></pre>

<p>How to sort each group by <code>Date</code> desc and take the first entry?</p>

<p><strong>EDIT</strong></p>

<p>I have updated my query to </p>

<pre><code>    var query= db.Feedback.GroupBy(f =&gt; new { f.Name, f.Comment })
                .Select(a =&gt; a.AsEnumerable())
                .Select(b =&gt; b.OrderByDescending(f =&gt; f.Date)
                .Select(c=&gt;new{c.Name,c.Date,c.Comment}));
</code></pre>

<p>...and doing the last Select prevents having reference loop error in JsonSerializer.</p>

<p><em>My Data should look like this</em></p>

<p>Name:Name1
Date:28 Sept
Comment:comment text</p>

<p>Name:Name2
Date: 15 Aug
Comment:comment text</p>

<p><em>...but it looks like that:</em></p>

<p>Name:Name1
Date:28 Sept
Comment:comment text</p>

<p>Name:Name2
Date: 15 Aug
Comment:comment text</p>

<p>Name:Name1
Date: 01 Aug
Comment:comment text</p>

<p>...AND HERE IS THE SOLUTION</p>

<pre><code>        var query= db.Feedback
                .GroupBy(f =&gt; new { f.Name})
                .Select(a =&gt; a.AsEnumerable())
                .Select(b =&gt; b.OrderByDescending(f =&gt; f.Date)
                    .Select(c =&gt; new { c.Name, c.Date, c.Comment})
                    .FirstOrDefault());
</code></pre>