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.
I’m not seeing the Cast() method on the System.Array class…
It’s an extension method on IEnumerable which Array implements. Looks like it was introduced in .Net Framework 3.5.
http://msdn.microsoft.com/en-us/library/bb341406%28v=vs.95%29.aspx
Thanks, exactly what I need!