Ordering Collections with enum properties using LINQ

Interesting find today. To order a collection based on an enum alphabetically, you can use LINQ as per the example below:

    var collection = new List<myCustomObjectWithEnumProperty>();
    var sortedCollection = collection.OrderBy(c=>c.EnumProperty.ToString());

To order a collection based on an enum by value, you can do the following:

    var collection = new List<myCustomObjectWithEnumProperty>();
    var sortedCollection = collection.OrderBy(c=>(int)c.EnumProperty);

Simple as that!

Happy coding...


  • Share this post on
comments powered by Disqus