Sort a List by enum where enum is out of order

前端 未结 7 791
轻奢々
轻奢々 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:19

    If you are about to get this working with Entity Framework (EF), you would have to spread out your enum in your OrderBy as such:

    messageList.OrderBy(m => 
        m.MessageType == MessageType.Boo ? 0 :
        m.MessageType == MessageType.Bar ? 1 :
        m.MessageType == MessageType.Foo ? 2 :
        m.MessageType == MessageType.Doo ? 3 : 4
    );
    

    This creates a sub select with CASE WHEN, then ORDER BY on that temporary column.

    0 讨论(0)
提交回复
热议问题