Skip to content

Instantly share code, notes, and snippets.

@timiles
Created February 6, 2018 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timiles/ad3c0238fd34746ee57ea3b2107ffbb3 to your computer and use it in GitHub Desktop.
Save timiles/ad3c0238fd34746ee57ea3b2107ffbb3 to your computer and use it in GitHub Desktop.
Convert enum type to readable dictionary values
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