tags:

views:

17

answers:

2

I have a bunch of news articles and I want to select the most recent one using Linq to Sql. I have an MVC action method like so

[ChildActionOnly]
public ActionResult LatestNews()
{
    var article = mhndb.NewsArticles.Single();

    return PartialView("LatestNews", article);
}

I would like to know the syntax for selecting the most recent item in the NewsArticles collection using Linq. Thanks in advance.

+2  A: 

The simplest option is to use OrderByDescending and then FirstOrDefault():

var article = mhndb.NewsArticles.OrderByDescending(a => a.PostedTime)
                                .FirstOrDefault();

(If you use First, it will throw an exception if there are no entries. With FirstOrDefault, it will return null.)

If you want to use a query expression, it will look something like this:

var article = (from a in mhndb.NewsArticles
               orderby a.PostedTime descending
               select a).FirstOrDefault();
Jon Skeet
Thanks Jon, this worked!
Gallen
A: 

Use something like

mhndb.NewsArticles.OrderBy(a => a.publishDate).Last()
Frank
Using `Single` will blow up if there's more than one entry. And using OrderBy instead of OrderByDescending will give the *earliest* entry rather than the most recent one.
Jon Skeet