uhateoas
9/28/2017 - 8:28 AM

Converting Enumeration Elements to Strings

The code uses the Regex framework to perform the insertion of spaces into the enumeration string. It assumes that MyEnumeration.DateOfBirth should transform to "Date Of Birth" whereas ExampleEnumeration.RawMRZData should become "Raw MRZ Data" and not "Raw M R Z Data".

You can of course modify the conversion to suit your own needs. For example, you might wish to replace " To " with " to ".

When performing many conversions, it makes sense to store the enumerations and their string representations in a dictionary, thereby reducing the execution time overhead.

The EnumItemMap class encapsulates enumeration conversion and an enumeration string dictionary:

(source https://www.codeproject.com/Tips/1207697/How-to-Generate-Element-Names-for-an-Enumeration)

public class EnumItemMap
{
    /*
     * Given an enum, construct a map where the keys are the enum items
     * and the values are string descriptions of each item. Example:
     *
     * {TheFirst, "The First"},
     * {TheSecond, "The Second"},
     * {AndTheLast, "And The Last"},
     *
     * Thus each enum item is converted to text and split at each capital letter.
     */
    public static Dictionary<T, string> Build<T>() where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum)
        {
            throw new ArgumentException
              ("Error: EnumItemMap.Build<T>() => T must be an enumerated type");
        }

        Dictionary<T, string> map = new Dictionary<T, string>();
        var values = Enum.GetValues(typeof(T));
        foreach (var item in values)
        {
            var r = new System.Text.RegularExpressions.Regex(
                @"(?<=[^A-Z])(?=[A-Z]) | (?=[A-Z][^A-Z])",
                System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace);

            map[(T)item] = r.Replace(item.ToString(), " ");
        }
        return map;
    }
}