using System.ComponentModel.DataAnnotations; using System.Reflection; namespace NetinaShop.Common.Extensions { public enum DisplayProperty { Description, GroupName, Name, Prompt, ShortName, Order } public static class EnumExtensions { public static IEnumerable GetEnumValues(this T input) where T : struct { if (!typeof(T).IsEnum) throw new NotSupportedException(); return Enum.GetValues(input.GetType()).Cast(); } public static IEnumerable GetEnumFlags(this T input) where T : struct { if (!typeof(T).IsEnum) throw new NotSupportedException(); foreach (var value in Enum.GetValues(input.GetType())) if ((input as Enum).HasFlag(value as Enum)) yield return (T)value; } public static string ToDisplay(this Enum value, DisplayProperty property = DisplayProperty.Name) { AssertExtensions.NotNull(value, nameof(value)); var attribute = value.GetType().GetField(value.ToString()) .GetCustomAttributes(false).FirstOrDefault(); if (attribute == null) return value.ToString(); var propValue = attribute.GetType().GetProperty(property.ToString()).GetValue(attribute, null); return propValue.ToString(); } public static Dictionary ToDictionary(this Enum value) { return Enum.GetValues(value.GetType()).Cast().ToDictionary(p => Convert.ToInt32(p), q => ToDisplay(q)); } } }