Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ按列x排序,如果为空,则取列y_C#_Sql_Linq - Fatal编程技术网

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

C# LINQ按列x排序,如果为空,则取列y,c#,sql,linq,C#,Sql,Linq,我正在使用以下数据模型构建一个简单的消息传递系统: public partial class Conversation { public Conversation() { this.Messages = new HashSet<Message>(); this.Customers = new HashSet<Customer>(); this.MessagingHubConnections = new Has

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

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; }
}

任何可以帮助我的人?

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);
var orderedConversations=conversations
.OrderByDescending(c=>
c、 信息
.选择(x=>x.TimeSend)
.OrderByDescending(x=>x)
.FirstOrDefault()??
c、 时间(已创建);

你的意思是
对话
(带有
s
)是
对话
IQueryable
,而不是
客户
?我的坏。我会修正它这就是我得到的:
'ICollection'不包含'Select'的定义,并且找不到接受第一个'ICollection'类型参数的扩展方法'Select'(您是否缺少[…]引用?
我立即从您的答案中复制粘贴了一个副本。变量
x
c
在我的代码中没有在其他任何地方使用。@JelleKerkstra my bad,Forget
Select
采用两种泛型类型。请参阅更新的答案。
var orderedConversations = conversations
    .OrderByDescending(c => 
        c.Messages
            .Select<Message, DateTime?>(x => x.TimeSend)
            .OrderByDescending(x => x)
            .FirstOrDefault() ??
        c.TimeCreated);