gpt4 book ai didi

c# - LINQ 按 x 列排序,如果为空则取 y 列

转载 作者:行者123 更新时间:2023-11-30 23:14:21 25 4
gpt4 key购买 nike

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

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 .下面的代码是我现在拥有的,但是当对话没有消息时,这显然不起作用。变量 conversations在下面的代码中是一个 IQueryable<Conversation> .

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

谁能帮帮我?

最佳答案

通过在 Max()-ing 之前将 TimeSend 投影到 DateTime? 中,您可以获得(DateTime?)null 当集合为空而不是获取 InvalidOperationException。然后,您可以使用 TimeCreated 对这个结果进行空合并:

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

关于c# - LINQ 按 x 列排序,如果为空则取 y 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com