开发者

LINQ to Entities - refining a query

I'm having a bit of a problem trying to refine/refactor a LINQ to Entities query. Here's what I currently have:

public List<Artic开发者_StackOverflow中文版le> LastFive()
{
    return _siteDB.Articles.OrderByDescending(a => a.LastModified).Take(5).ToList();
}

What I'd like to do is, instead of returning a list of the five most recent Articles, I'd like to simply get the Title and ID of the five most recent articles. I'd like to keep the method chaining intact, if possible (I like it from a style standpoint), but I'm not sure what to put for Select() using method chaining. I'm also not sure what to put as my method's return value since I won't be returning full Article entities, but only selected properties from them. List<IQueryable>?


It's better to create a typed class:

public class ArticlePreview
{
    public int ID {get;set;}
    public string Title {get;set;}
}

then:

public List<ArticlePreview> LastFive()
{
    return _siteDB.Articles.OrderByDescending(a => a.LastModified)
                  .Take(5).Select(a => new ArticlePreview(){ Title = a.Title,
                                                             ID = a.ID })
                  .ToList();
}

or, since you are using C# 4.0, you can choose what properties to return:

    public static List<dynamic> LastFive(Func<Article, dynamic> func)
    {
        return _siteDB.Articles.OrderByDescending(a => a.LastModified)
                  .Take(5).Select(a => func(a)).ToList();
    }

To use it:

var articlePreviews = LastFive(a => new { a.Title, a.ID });
//articlePreviews[0].Title
//articlePreviews[0].ID


You should probably return a List of an actual class, but a class containing only the properties that you need.

public class ArticleTitle
{
    public string Title { get; set; }
    public int ID { get; set; }
}

So that your query becomes:

public List<ArticleTitle> LastFive()
{
    return _siteDB.Articles.OrderByDescending( a => a.LastModified )
                           .Select( a => new ArticleTitle
                            {
                                 Title = a.Title,
                                 ID = a.ID,
                            })
                           .Take( 5 )
                           .ToList();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜