我正在尝试在ASP.NET MVC中实现群发消息功能。我想显示特定ContactID的所有线程列表,显示该线程中的最新消息(无论它来自哪个)。我把桌子设置如下:
MessageID ThreadID MessageBody ContactID
10000004 300152,300160, msg1 300160
10000005 300152,300160, msg2 300160
10000008 300152,300160, msg3 300152
我能够显示按ThreadID分组的最新消息。例如:
ThreadID Count LatestMessage
300152,300160, 3 10000008
但是,如果我在group by之前添加Where子句(见下文),它将在执行group by之前首先过滤ContactID,并产生以下结果:
ThreadID Count LatestMessage
300152,300160, 2 10000005
以下是代码:
var result = from s in pdc.Messages
where s.ContactID == contactID
group new { s } by new { s.ThreadID } into d
let maxMsgID = d.Max(x => x.s.MessageID)
select new {
ThreadID = d.Key.ThreadID,
Count = d.Count(item => item.s.MessageType == GlobalConstants.MessageTypeText),
LastMessage = d.Where(x => x.s.MessageID == maxMsgID)
};
有没有办法通过然后过滤ContactID来进行分组?
答案 0 :(得分:0)
var result = from s in pdc.Messages
where s.ContactID == contactID
group new { s } by new { s.ThreadID } into d
select new {
ThreadID = d.Key,
Count = d.Count(item => item.s.MessageType == GlobalConstants.MessageTypeText),
LastMessage = d.select(x => x.s.MessageID).Max(),
};
希望它可以帮助你,度过美好的一天。