In this post I will try to show how to convert an enum to List in C#.
Enum is important to keep named integers. That is, if you want to use integer values with some readable names, enum has no competitor. So, listing all enum values sometimes becomes essential. So I have tried to implement this in the following code:
Enum is important to keep named integers. That is, if you want to use integer values with some readable names, enum has no competitor. So, listing all enum values sometimes becomes essential. So I have tried to implement this in the following code:
Reading enum values to a List object:
Let us declare a enum type first. then try to see how can we read this.
public enum DbActions
{
Add,
Update,
Delete,
Select,
Sort,
Filter,
Pagination,
Merg
}
{
Add,
Update,
Delete,
Select,
Sort,
Filter,
Pagination,
Merg
}
Now let us define our methods which will read enum to List.
public class EnumHelper
{
{
public static List<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use type constraints on value types, so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
{
Type enumType = typeof(T);
// Can't use type constraints on value types, so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
}
To use this method, you can use the following code:
var list = EnumHelper.EnumToList<DbActions>();
No comments:
Post a Comment