How do I convert an enum to a list in C#?

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EnumProject
{
    class Program
    {
        static List<EnumDto> list = new List<EnumDto>();

        static void Main(string[] args)
        {
            foreach (var item in Enum.GetValues(typeof(Unvan)))
            {
                list.Add(new EnumDto()
                {
                    Id = Convert.ToInt32(Convert.ChangeType(item, typeof(Int32)).ToString()),
                    Text = GetDisplayName((Enum)item)
                });
            }
        }

        public static String GetDisplayName(Enum t)
        {
            FieldInfo fi = t.GetType().GetField(t.ToString());

            DisplayAttribute[] attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Name;
            else
                return t.ToString();
        }
    }

    class EnumDto
    {
        public int Id { get; set; }

        public String Text { get; set; }
    }
}



namespace EnumProject
{
    [DataContract]
    public enum Unvan
    {
        [Display(Name = "Memur")]
        [EnumMember]
        Memur = 1,

        [Display(Name = "Tekniker")]
        [EnumMember]
        Tekniker = 2,

        [Display(Name = "Mühendis")]
        [EnumMember]
        Muhendis = 3,

        [Display(Name = "Şef")]
        [EnumMember]
        Sef = 4,

        [Display(Name = "Müdür")]
        [EnumMember]
        Mudur = 5,

        [Display(Name = "Daire Başkanı")]
        [EnumMember]
        DaireBaskani = 6
    }
}

Bir cevap yazın