按ID分组,并用Linq显示顶部1
本文关键字:显示 顶部 Linq 并用 ID 分组 | 更新日期: 2023-09-27 18:24:26
正在寻找一些关于使用实体框架和linq进行分组的建议。
因此,我有一个表"tbl_ChatLog",其中包含userID和sendToUserID等……使用这些数据,我试图显示每个"sendToUserID"的"Top 1"
所以在我的UI中,它看起来是这样的:
- 1001(包含多个,但显示顶部1)
- 1003(包含多个,但显示顶部1)
- 1008(包含多个,但显示顶部1)
- 1009(包含多个,但显示顶部1)
我的代码开始如下:
public static List<Chat> getChatMessage()
{
var entities = new FreeEntities();
//My ID
Business.User user = Business.User.getUserBySecurityToken();
List<Chat> chatMessages =
(
from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
select new Chat
{
uid = (int)cm.UserID,
sendToUserID = (int)cm.SendToUserID,
message = cm.Message, dateAdded = (DateTime)cm.DateAdded
}
).OrderByDescending(x => x.dateAdded).ToList();
return chatMessages;
}
希望你能帮我解决这个问题。分组似乎总是让我不知所措。
非常感谢
Terry
您可以使用groupby
:
List<Chat> chatMessages =
(from cm in entities.tbl_ChatLog
where cm.UserID == user.uid
orderby cm.DateAdded descending
group cm by cm.sendToUserID into grp
select new Chat
{
uid = grp.FirstOrDefault().UserID,
sendToUserID = grp.Key,
message = grp.FirstOrDefault().Message,
dateAdded = grp.FirstOrDefault().DateAdded
}).ToList()
这将为您提供一个按sendToUserID
分组的表数据列表,以及包含sendToUserID
在内的每个属性的每个组的第一个条目。
最初的问题是试图从每个唯一的"SendToUserId"中选择第一条消息,并按UserId分组,然后选择DTO是一场噩梦,但我设法找到了一个简单的解决方案。以下代码:
getFirstChatMessage()
{
var entities = new FreeEntities();
//User ID
Business.User user = Business.User.getUserBySecurityToken();
// Create new list of Chat
List<Chat> chatList = new List<Chat>();
var res = from c in entities.tbl_ChatLog
where c.UserID == user.uid
group c by c.UserID
into groups
select groups.OrderByDescending(p => p.DateAdded).FirstOrDefault();
foreach (var r in res)
{
chatList.Add(new Chat()
{
uid = (int)r.UserID,
sendToUserID = (int)r.SendToUserID,
message = (from m in entities.tbl_ChatLog where m.UserID == (int)r.SendToUserID
orderby r.DateAdded descending select m.Message).FirstOrDefault(),
dateAdded = (DateTime)r.DateAdded,
fullName = (from b in entities.tbl_Bio where b.UserID == (int)r.SendToUserID
select b.FirstName + " " + b.SurName).FirstOrDefault()
});
}
return chatList;
}