Sort a List by enum where enum is out of order

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

    You can build a mapping dictionary dynamically from the Enum values with LINQ like this:

      var mappingDIctionary = new List((string[])Enum.GetNames(typeof(Hexside)))
                        .OrderBy(label => label )
                        .Select((i,n) => new {Index=i, Label=n}).ToList();
    

    Now any new values added to the Enum n future will automatically get properly mapped.

    Also, if someone decides to renumber, refactor, or reorder the enumeration, everything is handled automatically.

    Update: As pointed out below, Alphabetical ordering was not called for; rather a semi- alphabetical ordering, so essentially random. Although not an answer to this particular question, this technique might be useful to future visitors, so I will leave it standing.

提交回复
热议问题