I think your code is beautiful!
The only improvement will be the placement of code in the extension method.
EDIT:
When I think about this, you want to use Enum as in the definition, and not as an instance of enum, which is required for extension methods.
I found this question that solves it very well:
public class SelectList { // Normal SelectList properties/methods go here public static SelectList Of<T>() { Type t = typeof(T); if (t.IsEnum) { var values = from Enum e in Enum.GetValues(t) select new { ID = e, Name = e.ToString() }; return new SelectList(values, "Id", "Name"); } return null; } } // called with var list = SelectList.Of<Things>();
Only you might want to return a Dictionary<int, string> and not a SelectList , but you are a SelectList idea.
EDIT2:
Here we give an example of code that covers the case you are looking at.
public class EnumList { public static IEnumerable<KeyValuePair<T, string>> Of<T>() { return Enum.GetValues(typeof (T)) .Cast<T>() .Select(p => new KeyValuePair<T, string>(p, p.ToString())) .ToList(); } }
Or this version, possibly where the key is int
public class EnumList { public static IEnumerable<KeyValuePair<int, string>> Of<T>() { return Enum.GetValues(typeof (T)) .Cast<T>() .Select(p => new KeyValuePair<int, string>(Convert.ToInt32(p), p.ToString())) .ToList(); } }
Mikael Östberg Apr 12 2018-11-11T00: 00Z
source share