Created
February 6, 2018 19:16
-
-
Save timiles/ad3c0238fd34746ee57ea3b2107ffbb3 to your computer and use it in GitHub Desktop.
Convert enum type to readable dictionary values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
public static class EnumHelper | |
{ | |
public static IDictionary<int, string> ToDictionary(this Type enumType) | |
{ | |
return Enum.GetValues(enumType).Cast<object>().ToDictionary(x => (int)x, x => GetDescription(enumType, x.ToString())); | |
} | |
private static string GetDescription(Type enumType, string name) | |
{ | |
var descriptionAttribute = enumType.GetField(name) | |
.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute; | |
return descriptionAttribute != null | |
// use [Description] if exists | |
? descriptionAttribute.Description | |
// otherwise, convert value to sentence case, handling acronyms | |
: Regex.Replace(name, @"(\B[A-Z]+?(?=[A-Z][^A-Z])|\B[A-Z]+?(?=[^A-Z]))", " $1"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment