LINQ to SQL - Group By/Where
I'm trying to implement a group messaging feature in ASP.NET MVC. I want to display a list of all threads for a specific ContactID, displaying the latest message in that thread (no matter who it's from). I've set up my table as below:
MessageID ThreadID MessageBody ContactID
10000004 300152,300160, msg1 300160
10000005 300152,300160, msg2 300160
10000008 300152,300160, msg3 300152
I was able to display the latest message grouped by ThreadID. Ex:
ThreadID Count LatestMessage
300152,300160, 3 10000008
However, if I add the Where clause before the group by (see below), it'll filter on ContactID first before doing the group by, and producing this result:
ThreadID Count LatestMessage
300152,300160, 2 10000005
Here's the code:
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.Mes开发者_StackOverflow中文版sageID)
select new {
ThreadID = d.Key.ThreadID,
Count = d.Count(item => item.s.MessageType == GlobalConstants.MessageTypeText),
LastMessage = d.Where(x => x.s.MessageID == maxMsgID)
};
Is there a way to do the group by and then filter on ContactID?
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(),
};
Hope it can help you and have a nice day.
精彩评论