1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I run this I get an error: Sequence contains no elements
@ygetarts, This is because one of the items in matchList didn't contain any messages, I've edited the code to support it.
0

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

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)

1 Comment

I'm using VS2013 so I modified this to be var newList = matchList.OrderBy(match => match.Messages.OrderBy(m => m.SentDate).FirstOrDefault()); However, this returns the same error I get when I run the query in my OP: At least one object must implement IComparable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.