简体   繁体   English

如何使用Linq从每个用户获取单个最后一条记录

[英]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.

相关问题 如何使用LINQ从每个集合中获取最大版本的记录? - How to get maximum version of record from each set using LINQ? 如何将 SQL 查询转换为 LINQ(以获取每个预订状态的最后记录) - How to Convert SQL query to LINQ (to get last record each bookingStatus) 如何使用 LINQ 获取最后一条记录 - SQLite 中的实体框架 - How to Get Last Record Using LINQ - Entity Framework in SQLite 我应该如何使用 LINQ 获取最后一条记录? - How should I do to get the last record using LINQ? 使用linq从链接到另一个表的表中获取一条记录 - using linq to get a single record from a table linked to another table 使用LINQ获取组的最后一条记录 - Get the last record of group using LINQ 如何使用Linq获取每个组中的第一条记录 - How to get first record in each group using Linq 如何使用LINQ从具有多个参数的单个表中搜索记录? - how to search record from single table with multiple parameters using LINQ? 如何使用 SQL Server 中的 Linq 获取不同的记录名称及其每个记录计数以绑定到 C# 中的 gridview - How to get the distinct record name and its each record count to bind to gridview in C# using Linq from SQL Server 如何每次使用asp.net中的linq和multiview控件从数据库中获取单行 - how to get single row each time from database using linq and multiview control in asp.net
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM