Click here to Skip to main content
15,895,800 members
Articles / Programming Languages / C#
Tip/Trick

EnumHelper for DbEnum

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
9 May 2017MIT 7.2K   3  
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

C#
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, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior) Self Employed
South Africa South Africa
I am a well seasoned developer with 18 years experience in the industry and have been working on C# since .Net 1 made its debut, which is since 2002 and remember all the hardcore work that needed to be done and has seen how it evolved. I have written multitudes of solutions in .Net for many customers and always learn something new.

Needles to say, my repertoire does not start and end with .Net and includes tech knowledge from database, servers, applications across various streams, not just Microsoft technologies.

In the future I will attempt to hand some of my knowledge down to the community, since it has helped me so many times over the years.

Comments and Discussions

 
-- There are no messages in this forum --