Simple way to use enums for sorting in Optimizely Search & Navigation

As stated in the Optimizely Search & Navigation developer documentation on Sorting, “Sorting is supported for numerical types such as int, double, DateTime, and string”. This means that you will get an error from EPiServer.Find.SortingValidationHelper.ValidateSupportedType if you attempt to sort on an enum field.

System.NotSupportedException: Sorting by expressions of type Models.MyEnum is not supported. Change the sorting expression x => (x As ISearchHit).TheEnum. Supported types to sort by are native value types such as int, DateTime, nullable versions of the same and strings.
public enum MyEnum
{
  None = 0,

  SomeValue = 1,

  SomeOtherValue = 2
}

public interface ISearchHit
{
  MyEnum TheEnum { get; set; }
}

[ContentType(...)]
public class MyPage : PageData, ISearchHit
{
  [Display(...)]
  public virtual TheEnum { get; set; }
}

// The sorting part of the query.
searcher.OrderBy(x => (x as ISearchHit).TheEnum)

There are of course various solutions to this problem, but here is a rather simple one: turn the enum into a string and use that for sorting instead.

public interface ISearchHit
{
  MyEnum TheEnum { get; set; }

  string TheEnumString { get; }
}

[ContentType(...)]
public class MyPage : PageData, ISearchHit
{
  [Display(...)]
  public virtual TheEnum { get; set; }

  [Ignore]
  public virtual TheEnumString =>Enum.GetName(typeof(MyEnum), this.TheEnum);
}

// The sorting part of the query.
searcher.OrderBy(x => (x as ISearchHit).TheEnumString)

TheEnumString will be calculated when Optimizely Search & Navigation index the page. A simple method call like this in a getter is OK. However, if you start doing more complex stuff like making Http requests or using asynchronous code in this fashion, there are things that you would need to consider.

Drawbacks of this approach include adding more data to the index and having to reindex the content that you want to sort.