jpiccolo jpiccolo - 3 months ago 12
C# Question

Sort a List<T> by enum where enum is out of order

I have a List of messages.
Each message has a type.

public enum MessageType
{
Foo = 0,
Bar = 1,
Boo = 2,
Doo = 3
}


The enum names are arbitrary and cannot be changed.

I need to return the list sorted as: Boo, Bar, Foo, Doo

My current solution is to create a tempList, add the values in the order I want, return the new list.

List<Message> tempList = new List<Message>();
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Boo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Bar));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Foo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Doo));
messageList = tempList;


How can I do this with an IComparer?

Answer

An alternative to using IComparer would be to build an ordering dictionary.

var orderMap = new Dictionary<MessageType, int>() {
    { MessageType.Boo, 0 },
    { MessageType.Bar, 1 },
    { MessageType.Foo, 2 },
    { MessageType.Doo, 3 }
};

var orderedList = messageList.OrderBy(m => orderMap[m.MessageType]);
Comments