简体   繁体   中英

c# Sort a list of objects by a property of an object

I have a list of Match objects:

IEnumerable<Match> matches

Match looks like this

    public class Match
    {
    [JsonProperty("_id")]
    public string Id { get; set; }

    [JsonProperty("last_activity_date")]
    public string LastActivityDate { get; set; }

    [JsonProperty("messages")]
    public MatchMessage[] Messages { get; set; }

}

My MatchMessage class looks like this:

    public class MatchMessage
{
    [JsonProperty("_id")]
    public string Id { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }

    [JsonProperty("sent_date")]
    public string SentDate { get; set; }
}

Now, I want to sort my list of Matches by the SentDate property in MatchMessage and I'm having a very hard time figuring this out.

i tried:

var newList = matchList.OrderBy(match => match.Messages.OrderBy(x => x.SentDate));

but I get an error when I do that. I've been googling for a while and can't find a solution to this. How do I go about doing this?

This will order matchList by Ascending order by the Latest Message of each match.

var newList = matchList.OrderBy(
        match =>
            match.Messages.Any()
            ? match.Messages.Max(x => DateTime.Parse(x.SentDate))
            : DateTime.MaxValue);

Note: Given SentDate is properly DateTime formatted.

Your single Match may contain multiple messages, so there could be multiple SendDate for one Match .

To use SendDate from first message inside match:

var newList = matchList.OrderBy(match => match.Messages.FirstOrDefault()?.SendDate);

To use newest send date inside messages:

var newList = matchList.OrderBy(match => match.Messages.OrderBy(m => m.SendDate).FirstOrDefault()?.SendDate);

Warning: null-propagation from C# 6.0 used (only in VS 2015)

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