简体   繁体   中英

LINQ query for retrieving data from list

I have List collection of Message objects.

public class Message
{
    public int Id { get; set; }
    public string Body { get; set; }
    public string Sender { get; set; }
    public DateTime Timestamp { get; set; }
}

I want to get only one message with most recent Timestamp for each sender. How do I do it using LINQ?

You need to group by Sender and then get the Max Timestamp from each group like:

var query = list.GroupBy(r => r.Sender)
                .Select(grp => new
                {
                    Sender = grp.Key,
                    RecentTimeStamp = grp.Max(r => r.Timestamp)
                });

Or you can sort the TimeStamp in group by descending order and get the first element like:

var query = list.GroupBy(r => r.Sender)
                .Select(grp => new
                {
                    Sender = grp.Key,
                    RecentTimeStamp = grp.OrderByDescending(r => r.Timestamp).FirstOrDefault()
                });
var q = from n in table
        group n by n.Senderinto g
        select g.OrderByDescending(t=>t.Timestamp).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM