Generic Method To get values of an Enum
Recently I got a requirement of creating a generic method to pass an Enum Name & get all the Enum Names & Values.
Method will return a collection of following class objects.
public class EnumValueDto {
public string Id { get; set; }
public string Value { get; set; }
}
private IList<EnumValueDto > GetEnumValueList<T>()
{
IList<EnumValueDto > enumValueList = new List<EnumValueDto >();
var values = Enum.GetValues(typeof(T)).Cast<T>();
var enumerable = values as T[] ?? values.ToArray();
for (int i = 0; i < enumerable.Count(); i++)
{
enumValueList.Add(new EnumValueDto {
Id =((int)Enum.Parse(typeof (T), enumerable.ElementAt(i).ToString())).ToString(),
Value = enumerable.ElementAt(i).ToString() });
}
return enumValueList;
}
Hope this will be helpful.
Happy Coding !!!!!
Comments
Post a Comment