开发者

Selecting most recent news article in a collection with Linq to Sql

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.开发者_如何学PythonSingle();

    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.


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();


Use something like

mhndb.NewsArticles.OrderBy(a => a.publishDate).Last()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜