2010-11-15 104 views
0

我試圖在ASP.NET MVC中實現組消息功能。我想顯示特定ContactID的所有線程列表,並在該線程中顯示最新消息(不管來自哪個人)。我建立了如下表格:LINQ to SQL - 分組依據/ Where

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, 2 10000005 

ThreadID Count LatestMessage 
300152,300160, 3 10000008 

但是,如果我通過(見下文)組之前添加WHERE子句中,它會在第一次使用ContactID通過執行組,併產生這一結果之前過濾

這裏是代碼:

 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
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(), 
       }; 

希望它能幫助你,祝你有美好的一天。