我正在开发具有消息传递功能的应用程序。当用户删除一条消息时,它将用删除时间填充模型的两列之一,即SenderDeleted或RecieverDeleted。
该应用程序还将具有一个选项卡,该选项卡显示与用户(作为发件人和收件人)有关的所有已删除邮件。我希望删除的邮件列表按这两列的总和进行排序。
因此用户将看到消息2,消息1,消息3
答案 0 :(得分:1)
给出:
public class Message
{
public Nullable<DateTime> SendDate {get;set;}
public Nullable<DateTime> ReceiveDate {get;set;}
public string Note {get;set;}
}
已初始化:
List<Message> messages = new List<Message>
{
new Message { SendDate = new DateTime(2000, 1, 1, 9, 0, 0), ReceiveDate = null, Note = "Message 1: User is sender" },
new Message { SendDate = null, ReceiveDate = new DateTime(2000, 1, 1, 8, 0, 0), Note = "Message 2: User is recipient" },
new Message { SendDate = new DateTime(2000, 1, 1, 13, 0, 0), ReceiveDate = null, Note = "Message 3: User is sender" },
new Message { SendDate = null, ReceiveDate = new DateTime(2000, 1, 1, 9, 0, 0), Note = "Message 4: User is recipient" },
};
您可以创建自定义Comparer
来对可为空的日期进行排序,例如:
public class NullableDateComp : IComparer<Nullable<DateTime>>
{
public int Compare([AllowNull] DateTime? x, [AllowNull] DateTime? y)
{
if (x is null && y is null)
{
return 0;
}
if (x is null)
{
return 1;
}
if (y is null)
{
return -1;
}
return x.Value.CompareTo(y.Value);
}
}
可以通过以下方式将Comparer
与OrderBy
和ThenBy
组合:
messages.OrderBy(x => x.ReceiveDate, new NullableDateComp()).ThenBy(x => x.SendDate, new NullableDateComp())
输出:
Message 2: User is recipient
Message 4: User is recipient
Message 1: User is sender
Message 3: User is sender