简体   繁体   English

LINQ to SQL给定ID的最新记录集?

[英]LINQ to SQL most recent set of records for a given ID?

This one should be easy. 这应该很容易。

I have a Reviews table with records. 我有一个带有记录的评论表。 The columns are EntityID, UserID, Body, DateModified. 这些列是EntityID,UserID,Body和DateModified。 A User can submit multple entries for an Entity. 用户可以为实体提交多个条目。 I want to select all the Reviews that are the most recent entries for a given entity per UserID. 我想为每个UserID选择给定实体的最新条目的所有评论。

So the table might look like this: 因此表可能如下所示:

EntityID     UserID     Body     DateModified
1            101        "hey"    8/22/2010 11:36:47 PM
1            101        "dude"   8/11/2010 04:15:43 PM
1            108        "brah"   8/21/2010 11:31:11 PM
1            108        "sup?"   8/14/2010 10:00:00 PM

I've got something like this: 我有这样的事情:

 var itemReviews = db.Reviews
                             .Where(x => x.EntityID == EntityID)
                             .OrderByDescending(x => x.DateSubmitted)
                             ;

What do I need to add to get only the records for the most recent EntityID? 我需要添加什么才能只获取最新的EntityID的记录?

Thanks. 谢谢。

In order to get the single most recent review: 为了获得最新的评论:

var mostRecentReview = db.Reviews
                         .Where(x => x.EntityID == EntityID)
                         .OrderByDescending(x => x.DateSubmitted)
                         .First();

In order to get the most recent review for each user: 为了获得每个用户的最新评论:

var reviews = db.Reviews
                .Where(x => x.EntityID == EntityID)
                .GroupBy(x => x.UserID)
                .Select(gr => new {
                    UserID = gr.Key,
                    MostRecentReview = gr.OrderByDescending(x => x.DateSubmitted)
                                         .First()
                });

If you want a set of items returned (sql top/limit) you can use Take 如果要返回一组项目(SQL最高/限额),则可以使用Take

var itemReviews = db.Reviews
                    .Where(x => x.EntityID == EntityID)
                    .OrderByDescending(x => x.DateSubmitted)
                    .Take(4);

If you also want to do some paging you can use Skip 如果您还想进行一些分页,则可以使用“ Skip

var itemReviews = db.Reviews
                    .Where(x => x.EntityID == EntityID)
                    .OrderByDescending(x => x.DateSubmitted)
                    .Skip(pageNo *pageSize).Take(pageSize);

many way you can use,one of the way is : 您可以使用多种方式,其中一种是:

var mostRecentReview = db.Reviews
                     .Where(x => x.EntityID == EntityID).Max(x =>x.DateModified);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM