I was planned to fill my country List drop down using Enum. So i need Enum value description and that index value. My Conditions:
My Enum :
public enum CountryListEnum
{
[Description("United Kingdom")]
UnitedKingdom = 0,
[Description("United States")]
UnitedStates = 1,
[Description("Afghanistan")]
Afghanistan = 2,
[Description("Albania")]
Albania = 3,
}
My Model :
public class CountryModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
To get the index value, you can just cast the enum to an int. Getting the description attribute is a little more involved. Maybe something like this
public enum CountryListEnum
{
[Description("United Kingdom")]
UnitedKingdom = 0,
[Description("United States")]
UnitedStates = 1,
[Description("Afghanistan")]
Afghanistan = 2,
[Description("Albania")]
Albania = 3,
}
static void Main(string[] args)
{
foreach (var country in Enum.GetValues(typeof(CountryListEnum)).Cast<CountryListEnum>())
{
Console.WriteLine($"Index: {(int)country}");
Console.WriteLine($"Description: {GetDescription(country)}");
}
}
public static string GetDescription(Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
System.Reflection.FieldInfo field = type.GetField(name);
if (field != null)
{
if (Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) is DescriptionAttribute attr)
{
return attr.Description;
}
}
}
return null;
}
I think this should help you with an implementation.
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
CountryModel myModel = new CountryModel();
myModel.CountryId = item.GetHashCode();
myModel.CountryName = item.ToString();
}
Edit
As others have pointed the above will not retrieve the description. Here is an update in how to implement the retrial of description attribute.
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
CountryModel myModel = new CountryModel();
myModel.CountryId = item.GetHashCode();
var type = typeof(CountryListEnum);
var memInfo = type.GetMember(item.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
var description = ((DescriptionAttribute)attributes[0]).Description;
myModel.CountryName = description;
}
I think, this is what you looking for.
var model = new List<CountryModel>();
foreach (var item in Enum.GetValues(typeof(CountryListEnum)))
{
model.Add(new CountryModel
{
CountryId = (int)item,
CountryName = ((DescriptionAttribute)item.GetType().GetField(item.ToString()).GetCustomAttribute(typeof(DescriptionAttribute), false)).Description
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.