LINQ Where存在GROUP BY

时间:2011-04-03 16:24:22

标签: sql linq group-by exists

如何在LINQ中转换它?

SELECT B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT
FROM MESSAGES B
WHERE EXISTS ( SELECT A.SENDER
        FROM MESSAGES A
    WHERE A.SENDER = B.SENDER
    GROUP BY A.SENDER
    HAVING B.SMSTIME = MAX( A.SMSTIME))
GROUP BY B.SENDER, B.SENDNUMBER, B.SMSTIME, B.SMSTEXT ;

非常感谢:)

EDIT !!

已解决:

  var Condition = "order by SMSTime desc";      

  IEnumerable<ClassMessaggio> messaggi = Database.Select<ClassMessaggio>(Condition);; // Load all but sorted

  ElencoConversazioni =  messaggi.GroupBy(m => new { m.Number })
                .Select(g => g.OrderByDescending(m => m.SMSTime).First()).ToObservableCollection();

2 个答案:

答案 0 :(得分:1)

尝试

db.Messages.Where(b => b.SmsTime == Messages.Where(a => a.Sender == b.Sender)
                                            .Max(a => a.SmsTime))

或者

db.Messsages.GroupBy(m => new { m.Sender, m.SendNumber })
            .Select(g => g.OrderByDescending(m => m.SmsTime).First())

db是您的DataContext。

答案 1 :(得分:0)

要显示会话列表以及“每个联系人的最后一条消息”,您可以尝试以下内容:

// a query to find the last Sms time per sender
var lastSmsQuery = from m in db.messages
                 group m by m.Sender into grouping
                 select new
                 {
                     Sender = grouping.Key,
                     LastSmsTime = grouping.Max(x => x.SmsTime)
                 };

// a query to find the messages linked to the last Sms per sender
var lastMessageQuery = from m in db.messages
                       join l in lastSmsQuery on new { m.Sender, m.SmsTime } equals new { l.Sender, l.LastSmsTime }
                       select m;

使用的2查询方法类似于今天早些时候的问题 - Convert SQL Sub Query to In to Linq Lambda