[英]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 我在其中有几列,但下一个问题是必需的:-用户ID-消息发送日期时间
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. 我想从每个用户那里获得最后一条消息,并且不了解如何为此目的编译所需的linq查询。
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? 有关详细信息,几个用户已向我发送了50-100条消息,但我想按日期时间从每个用户中只获取最后一个,如何使用linq查询呢?
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. 应该像按用户ID过滤,按日期排序并取得最高记录一样简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.