我正在使用以下数据模型构建一个简单的消息传递系统:

public partial class Conversation
{
    public Conversation()
    {
        this.Messages = new HashSet<Message>();
        this.Customers = new HashSet<Customer>();
        this.MessagingHubConnections = new HashSet<MessagingHubConnection>();
    }

    public int Id { get; set; }
    public int BoatId { get; set; }
    public System.DateTime TimeCreated { get; set; }

    public virtual ICollection<Message> Messages { get; set; }
    public virtual Boat Boat { get; set; }
    public virtual ICollection<Customer> Customers { get; set; }
    public virtual ICollection<MessagingHubConnection> MessagingHubConnections { get; set; }
}

public partial class Message
{
    public int Id { get; set; }
    public int ConversationId { get; set; }
    public string Text { get; set; }
    public bool IsRead { get; set; }
    public System.DateTime TimeSend { get; set; }
    public int CustomerId { get; set; }

    public virtual Conversation Conversation { get; set; }
    public virtual Customer Customer { get; set; }
}


当客户打开其帐户仪表板时,我要显示所有对话的列表。这应该根据以下规则进行排序:列表中的第一个对话是带有最新Message.TimeSent消息的对话。如果对话中没有消息,则必须选择Conversation.TimeCreated
下面的代码是我现在拥有的,但是当对话没有消息时,这显然不起作用。以下代码中的变量conversationsIQueryable<Conversation>

var orderedConversations = conversations.OrderByDescending(c => c.Messages.Max(m => m.TimeSend));


有人可以帮助我吗?

最佳答案

通过在TimeSend之前将DateTime?投影到Max()中,可以在集合为空时获得(DateTime?)null而不是获取InvalidOperationException。然后,您可以使用TimeCreated将结果空置:

var orderedConversations = conversations
    .OrderByDescending(c =>
        c.Messages
            .Select<Message, DateTime?>(x => x.TimeSend)
            .OrderByDescending(x => x)
            .FirstOrDefault() ??
        c.TimeCreated);

10-05 21:31