Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

EnumHelper for DbEnum

0.00/5 (No votes)
9 May 2017 1  
Just an EnumHelper class for re-use in DbEnum

Introduction

This helper was written to supply the enum over an Web Api call to list the enum/flags values and display strings, that will still match the code's ordinal value.  It was then later used to collect data and seed enum's into the databse.

By setting the DisplayAttribute on the enum and setting the Description property, this helper will assist with getting the "displaystring".  This is very handy if you want to use human readable text instead of the ordinal's key.

Used in DbEnum & IDbEnum: https://www.codeproject.com/Reference/1186336/DbEnum

public static class EnumHelper
{
    public static IEnumerable<dynamic> GetStruct<TEnum>() where TEnum : struct
    {
        return (from v in GetPrivateDisplayList<TEnum>()
                select new { Id = v, Description = v.ToString() });
    }

    public static IEnumerable<dynamic> GetDisplayList<TEnum>() where TEnum : struct
    {
        return (from v in GetPrivateDisplayList<TEnum>()
                select new { Id = v, Description = v.GetDisplayString() });
    }

    public static string GetDisplayString(this Enum source)
    {
        var da = source.GetDisplayAttribute();
        return da != null ? da.Description : source.ToString();
    }

    private static IEnumerable<Enum> GetPrivateDisplayList<TEnum>() where TEnum : struct
    {
        var ti = typeof(TEnum).GetTypeInfo();
        if (!ti.IsEnum) return null;

        return ti.GetEnumValues().Cast<Enum>();
    }

    private static DisplayAttribute GetDisplayAttribute(this Enum source)
    {
        var fi = source.GetType().GetTypeInfo().GetField(source.ToString());
        return fi.GetCustomAttribute<DisplayAttribute>();
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here