tags:

views:

48

answers:

3

This one should be easy.

I have a Reviews table with records. The columns are 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.

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?

Thanks.

+3  A: 

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()
                });
Timwi
You may use FirstOrDefault() instead of First() if you are not sure you have any items in the result set, then you get null back instead of an exception when no items match the condition.
Albin Sunnanbo
The second part got it. Thank you!
johnnycakes
A: 

If you want a set of items returned (sql top/limit) you can use 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

var itemReviews = db.Reviews
                    .Where(x => x.EntityID == EntityID)
                    .OrderByDescending(x => x.DateSubmitted)
                    .Skip(pageNo *pageSize).Take(pageSize);
Albin Sunnanbo
Downvote? Is there an explanation so that I might learn from any mistakes?
Albin Sunnanbo
A: 

many way you can use,one of the way is :

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