简体   繁体   English

c#按对象的属性对对象列表进行排序

[英]c# Sort a list of objects by a property of an object

I have a list of Match objects: 我有一个Match对象列表:

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: 我的MatchMessage类看起来像这样:

    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. 现在,我想通过MatchMessage中的SentDate属性对匹配列表进行排序,我很难搞清楚这一点。

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. 这将按每个匹配的最新消息按升序排序matchList

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. 注意:给定SentDate是正确的DateTime格式。

Your single Match may contain multiple messages, so there could be multiple SendDate for one Match . 您的单个Match可能包含多个消息,因此一个Match可能有多个SendDate

To use SendDate from first message inside match: 要在匹配内的第一条消息中使用SendDate:

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) 警告:使用C#6.0的空传播(仅在VS 2015中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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