Reputation: 973
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
Upvotes: 2
Views: 5090
Reputation: 820
You could use this snippet:
Letter[] allletters = Enum.GetValues(typeof(Letter)).Cast<Letter>().ToArray();
var sortedLetters = allletters.OrderBy(l => l.ToString());
Upvotes: 4
Reputation: 476557
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 Enum.GetName(l.Letter.GetType(),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.
Upvotes: 3
Reputation: 9396
Try the following:
Letter[] letters = (Letter[])Enum.GetValues(typeof(Letter));
IEnumerable<Letter> sorted = values.OrderBy(v => v.ToString());
Upvotes: 0