Christopher Pitts
Christopher Pitts

Reputation: 1

Is there a way to sort a list by a combination of two columns in C#?

I'm working on an app with a messaging function. When a user deletes a message it will populate one of two columns in the model, SenderDeleted or RecieverDeleted with the time of deletion.

The app will also have a tab that shows all deleted messages related to the user (both as a sender and recipient). I want the list of deleted messages to be sorted by both of these columns combined.

So the user would see message 2, message 1, message 3

Upvotes: 0

Views: 55

Answers (1)

Hayden
Hayden

Reputation: 2988

Given:

public class Message
{
    public Nullable<DateTime> SendDate {get;set;}
    public Nullable<DateTime> ReceiveDate {get;set;}
    public string Note {get;set;}
}

Initialized:

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

You can create a custom Comparer to sort the dates that are nullable, for example:

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

The Comparer can be combined with OrderBy and ThenBy in the following way:

messages.OrderBy(x => x.ReceiveDate, new NullableDateComp()).ThenBy(x => x.SendDate, new NullableDateComp())

Output:

Message 2: User is recipient
Message 4: User is recipient
Message 1: User is sender
Message 3: User is sender

Upvotes: 1

Related Questions