Ivica
Ivica

Reputation: 39

How to get a single last record from each user using Linq

I have a table with personal messages.

I have in it several columns, but required for this question are the next: - user id - message sent datetime

I want to get the last one message from each user and don't understand how to compile the needed linq query for this aim.

For details, several users have sent me 50-100 messages, but I want to get from each user only the last one by datetime, how do it using linq query?

Upvotes: 1

Views: 1380

Answers (1)

BenjaminPaul
BenjaminPaul

Reputation: 2931

Without any code to show me regarding your schema this is a complete guess but you should simply have to order by the datetime and take the first...

For a single user:

// Assuming you are using an Entity Framework context?
using (var context = new MyContext()) {
    var lastMessage = context.PersonalMessages.Where(u => u.UserId == userId).OrderByDescending(t => t.SentDate).FirstOrDefault();
}

Get last message for all users:

using (var context = new MyContext()) {
var lastMessages = context.PersonalMessages.GroupBy(pm => pm.UserId).SelectMany(g => g.OrderByDescending(pm => pm.SentDate).Take(1));
}

Should be as simple as filtering by the user id, ordering by date and taking the top record.

Upvotes: 2

Related Questions