我有Message对象的List集合。
public class Message
{
public int Id { get; set; }
public string Body { get; set; }
public string Sender { get; set; }
public DateTime Timestamp { get; set; }
}
我想只为每个发件人获取一条带有最新时间戳的邮件。如何使用LINQ进行操作?
答案 0 :(得分:1)
您需要按Sender
分组,然后从每个组中获取最大时间戳,如:
var query = list.GroupBy(r => r.Sender)
.Select(grp => new
{
Sender = grp.Key,
RecentTimeStamp = grp.Max(r => r.Timestamp)
});
或者您可以按降序对组中的TimeStamp进行排序,并获得第一个元素,如:
var query = list.GroupBy(r => r.Sender)
.Select(grp => new
{
Sender = grp.Key,
RecentTimeStamp = grp.OrderByDescending(r => r.Timestamp).FirstOrDefault()
});
答案 1 :(得分:0)
var q = from n in table
group n by n.Senderinto g
select g.OrderByDescending(t=>t.Timestamp).FirstOrDefault();