Sort a List by enum where enum is out of order

前端 未结 7 816
轻奢々
轻奢々 2020-12-25 11:15

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

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

The enum

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 12:05

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

    var orderMap = new Dictionary() {
        { MessageType.Boo, 0 },
        { MessageType.Bar, 1 },
        { MessageType.Foo, 2 },
        { MessageType.Doo, 3 }
    };
    
    var orderedList = messageList.OrderBy(m => orderMap[m.MessageType]);
    

提交回复
热议问题