///
/// Generic EnumItem class for Enum item representation.
///
public class EnumItem
{
///
/// The enum index, it is a 1-based index.
///
/// The enum index value (1-based).
public int Index { get; set; }
public string Name { get; set; }
public object Value { get; set; }
}
///
/// Converts an Enum to a List of type EnumItem.
///
/// The type of enum to convert.
/// List of type EnumItem.
public static List EnumToList()
{
//Validate T is an enum
Type enumType = typeof(T);
if (enumType.BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
var valueArray = (T[])(Enum.GetValues(typeof(T)).Cast());
var nameArray = Enum.GetNames(typeof(T)).ToArray();
List enumItemList = new List();
for (int i = 0; i < valueArray.Length; i++)
{
string name = nameArray[i];
T value = valueArray[i];
enumItemList.Add(new EnumItem { Index = i + 1, Name = name, Value = value });
}
return enumItemList;
}
By calling
List myList = EnumToList() you will receive a 3-column list containing the 1-based index, the enum name, and the enum value.
No comments:
Post a Comment