For get display name value you should use System.Reflection. And then you could do this in simple way:
public enum TCountryNames
{
[Display(Name = "America")]
cnUSA = 1,
[Display(Name = "England")]
cnUK,
[Display(Name = "CHINA")]
cnCHN
}
public class EnumData
{
public int Id { get; set; }
public string? Name { get; set; }
}
public class MyClass
{
public static List<EnumData> GetEnumList()
{
var list = new List<EnumData>();
foreach (var e in Enum.GetValues(typeof(TCountryNames)))
{
list.Add(new EnumData
{
Id = (int)e,
Name = e.GetType()
.GetMember(e.ToString())
.First()?
.GetCustomAttribute<DisplayAttribute>()?
.GetName()
});
}
return list;
}
}
So to clarify:
- you create loop foreach enum
- take id by casting
- take name using reflaction - I added all needed protection against null exception
Output: [ { "Id": 1, "Name": "America" }, { "Id": 2, "Name": "England" }, { "Id": 3, "Name": "CHINA" } ]
Example: https://dotnetfiddle.net/XVL2LI