using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace Opsoft.NetCore.O3App.Shared { public static class EnumExtensions { public static TResult GetAttribute(this Enum source) where TResult : Attribute { var fieldInfo = source.GetType().GetField(source.ToString()); return fieldInfo?.GetCustomAttributes(false)?.FirstOrDefault(); } public static string GetDesc(this Enum source) { var descriptionAttribute = GetAttribute(source); return descriptionAttribute?.Description ?? source.ToString(); } public static string GetDescWithDefault(this Enum source, string defaultDesc = "") { var descriptionAttribute = GetAttribute(source); return (descriptionAttribute?.Description ?? defaultDesc).NullOrEmpty2Default(source.ToString()); } public static string GetDisplay(this Enum source, string defaultDesc = "") { var displayAttribute = GetAttribute(source); return (displayAttribute?.Display ?? defaultDesc).NullOrEmpty2Default(source.ToString()); } public static bool IsDefined(this Enum source, object value) { return Enum.IsDefined(source.GetType(), value); } public static int ToInt32(this Enum value) { return Convert.ToInt32(value); } } public static class Enum where E : Enum { public static IEnumerable GetValues() => Enum.GetValues(typeof(E)).Cast(); public static IEnumerable GetDescriptions() => GetValues().Select(e => e.GetDesc()); public static IEnumerable GetAttributes() where TResult : Attribute => GetValues().Select(e => e.GetAttribute()); public static IEnumerable> GetValueDescriptionPairs() => GetValues().Select(e => new KeyValuePair(Convert.ToInt32(e), e.GetDesc())); public static IEnumerable> GetDescriptionValuePairs() => GetValues().Select(e => new KeyValuePair(e.GetDesc(), Convert.ToInt32(e))); public static IEnumerable> GetEnumDescriptionPairs() => GetValues().Select(e => new KeyValuePair(e, e.GetDesc())); public static IEnumerable> GetEnumAttributePairs() where TResult : Attribute => GetValues().Select(e => new KeyValuePair(e, e.GetAttribute())); public static bool IsDefined(object value) { return Enum.IsDefined(typeof(E), value); } public static bool NotDefined(object value) { return !IsDefined(value); } } }