Wednesday, 22 June 2016

C# Convert enum into List

Convert enum into List in c#.

public static class EnumUtility
{

 //This method is used for get the attribute from the enum property. In this example I am using      //[Display(Name = "Super Admin")] attribute to override the display value of "SuperAdmin" enum.
    public static T GetEnumAttribute<T>(this Enum enumValue) where T : Attribute
    {
        var type = enumValue.GetType();
        var memeberInfo = type.GetMember(enumValue.ToString());
        var attributes = memeberInfo[0].GetCustomAttributes(typeof(T), false);
        return (T)attributes.FirstOrDefault();
    }

    //This is an extension method to get the display name attribute value of the enum property.
    public static string ToDisplayName(this Enum value)
    {
        var attribute = value.GetEnumAttribute<DisplayAttribute>();
        return attribute == null ? value.ToString() : attribute.Name;
    }

    public enum UserRole
    {
        [Display(Name = "Super Admin")]
        SuperAdmin = 1,
        Admin = 2,
        User = 3
    }
}

Now lets get list of this UserRole enum in c#.

public List<UserRole> GetRolesList()
        {
            var rolesEnum = (EnumUtility.UserRole[])Enum.GetValues(typeof(EnumUtility.UserRole));

            List<UserRole> types = new List<UserRole>();
            foreach (var type in rolesEnum)
            {
                types.Add(new UserRole
                {
                    RoleName = type.ToDisplayName(),
                    Id = (int)type
                });
            }

            return types;
        }

   public class UserRole
        {
            public int Id { get; set; }
            public string RoleName { get; set; }
        }

No comments:

Post a Comment