C# Enum Helper

Date: 2019-11-12
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Helpers
{
    public class EnumHelper
    {
        public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
            if (string.IsNullOrEmpty(value)) return defaultValue;
            if (!Enum.TryParse<T>(value, out var enumValue)) return defaultValue;
            return enumValue;
        }
        
    	public static string GetDescription<T>(T enumValue) where T : struct, IConvertible
    	{
    		if (!typeof(T).IsEnum) return null;
    		var description = enumValue.ToString();
    		var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
    		if (fieldInfo != null)
    		{
    			var attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
    			if (attrs != null && attrs.Length > 0)
    			{
    				description = ((DescriptionAttribute)attrs[0]).Description;
    			}
    		}
    		return description;
    	}

        public static IEnumerable<string> GetEnumDescriptionValues(Type enumType)
        {
            return Enum.GetNames(enumType)
                .Select(x =>
                {
                    var attributes = enumType.GetField(x).GetCustomAttributes(true);
                    var attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;
                    return attribute?.Description ?? x;
                });
        }

        public static T ParseEnumDescriptionValues<T>(string value) where T : IConvertible
        {
            value = value?.ToLowerInvariant()?.Trim();
            var enumType = typeof(T);
            Dictionary<string, int> d = GetEnumDict(enumType);
            var result = d.ContainsKey(value) ? d[value] : 0;
            return (T)Convert.ChangeType(result, Enum.GetUnderlyingType(typeof(T)));
        }

        private static Dictionary<string, int> GetEnumDict(Type enumType)
        {
            var d = new Dictionary<string, int>();
            Array.ForEach(Enum.GetNames(enumType), x =>
            {
                var v = Enum.Parse(enumType, x);
                var i = (int)v;

                d.Add(x.ToLowerInvariant(), i);

                var attributes = enumType.GetField(x).GetCustomAttributes(true);
                var attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;
                if (attribute != null && !d.ContainsKey(attribute.Description))
                    d.Add(attribute.Description?.ToLowerInvariant(), i);
            });
            return d;
        }
    }
}
public static class EnumUtils
{
	public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
	{
		if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
		if (string.IsNullOrEmpty(value)) return defaultValue;
		if (TryParseEnumDescriptionValues<T>(value, out var enumValue)) 
		{ 
			return enumValue;
		}
		if (Enum.TryParse<T>(value, out var enumValue2))
		{
			return enumValue2;
		}
		return defaultValue;
	}
	public static bool TryParseEnumDescriptionValues<T>(string inValue, out T value) where T : struct, IConvertible
	{
		var items = GetEnumDescriptionValues<T>();
		var item = items.FirstOrDefault(x => StringHelper.Equals(x.Item1, inValue));
		if (item != null) { 
			value = item.Item2;
			return true; 
		}
		value = default(T);
		return false;
	}
	public static IEnumerable<Tuple<string, T>> GetEnumDescriptionValues<T>() where T : struct, IConvertible
	{
		var enumType = typeof(T);
		return Enum.GetValues(enumType).Cast<T>().Select(x => new Tuple<string, T>(GetDescription(x) , x));
	}
	public static IEnumerable<string> GetEnumDescriptionValues(Type enumType)
	{
		return Enum.GetNames(enumType)
			.Select(x =>
			{
				var attributes = enumType.GetField(x).GetCustomAttributes(true);
				var attribute = attributes.FirstOrDefault(a => a is DescriptionAttribute) as DescriptionAttribute;
				return attribute?.Description ?? x;
			});
	}
	public static string GetDescription<T>(T enumValue) where T : struct, IConvertible
	{
		if (!typeof(T).IsEnum) return null;
		var description = enumValue.ToString();
		var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
		if (fieldInfo != null)
		{
			var attrs = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
			if (attrs != null && attrs.Length > 0)
			{
				description = ((DescriptionAttribute)attrs[0]).Description;
			}
		}
		return description;
	}
}
28440cookie-checkC# Enum Helper