简体   繁体   中英

How to order enum alphabetically rather than on int?

Let's say I want my user to be able to sort a table based on an enum value

My enum would look like this:

public enum Letter
{
    C= 0,
    A,
    B,
    E,
    D,            
}

A query could look like this:

var letters = from l in context.Example
                  orderby l.Letter
                  select l;

The ascending/descending order will be based on the enum int value rather than alphabetical order. Is there an easy way to programatically order it alphabetically? Obviously I could sort it myself in my Enum Class but this could become mundane work on larger enums.

How I want it to be sorted:

//A       ACTUAL  //C
//B       ACTUAL  //A
//C       ACTUAL  //B
//D       ACTUAL  //E
//E       ACTUAL  //D

You can use the Enum.GetName method (or ToString() if we can rely that this will return the name):

var letters = from l in context.Example
              orderby l.Letter
              select l;

This could also work if the l.Letter can return different enums. It will fail however if it returns a non-enum. This can be (un)wanted behavior. In case you use ToString() you thus compare the objects based on their name. But any object (normally) supports a ToString() method.

For example:

csharp> enum Foo {
      > A,
      > B,
      > C
      > }
csharp> enum Bar {
      > AB,
      > ZZ,
      > X
      > }
csharp> var l = new object[] {Foo.C,Foo.B,Bar.ZZ,Bar.AB,Bar.X,Foo.A};
csharp> from li in l orderby Enum.GetName(li.GetType(),li) select li;  
{ A, AB, B, C, X, ZZ }

That being said, it usually makes not much sense to mix enums together.

You could use this snippet:

Letter[] allletters =  Enum.GetValues(typeof(Letter)).Cast<Letter>().ToArray();
var sortedLetters = allletters.OrderBy(l => l.ToString());

Try the following:

Letter[] letters = (Letter[])Enum.GetValues(typeof(Letter));
IEnumerable<Letter> sorted = values.OrderBy(v => v.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM