Sorting C# Enum.GetValue(…)

This one caused me a bit of frustration.  Enum.GetValue(…) returns a non-generic Array.  I tried all manner of ways to sort it (short of writing my own quicksort).  If I typed Enum.GetValue(…).OrderBy, there is no OrderBy.  I found one post online that suggested something like:

Array.Sort(Enum.GetValue(…), (p, q) => p.CompareTo(q))

but try as I might, I couldn’t get that work.  Array.Sort is expecting an IComparer for the second parameter and I kept getting the error “Cannot convert lambda expression to type ‘System.Collections.IComparer’ because it is not a delegate type“.

I finally figured it out:

Enum.GetValues(…).Cast<enum type>().OrderBy(e => e.ToString()).

.Cast<type>() will cast the types in the IEnumerable it’s called on to the specified type and results in an IEnumerable<type> (which you can call .OrderBy(…) on).

BTW, I don’t really sort the Enum values on their .ToString().  Each Enum entry gets assigned “Display Text” via an Attribute and that’s what they’re sorted on.  I’ll do another post on that.

Advertisements
This entry was posted in Programming, Technology and tagged , , , , . Bookmark the permalink.

3 Responses to Sorting C# Enum.GetValue(…)

  1. I’m not seeing the Cast() method on the System.Array class…

  2. Yomodo says:

    Thanks, exactly what I need!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s