C# enum parse enumtype and name to retrieve enum

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp35
{
    internal class Program
    {

        static void Main(string[] args)
        {
            ParseEnumDemo();
            Console.ReadLine();
        }

        static void ParseEnumDemo()
        {
            List<string> namesList = new List<string>()
            {
                "Science","Technology","Engineering","Mathematics"
            };

            foreach (string name in namesList) 
            {
                var currentBookEnum=(BookEnum)Enum.Parse(typeof(BookEnum), name);
                Console.WriteLine($"{currentBookEnum},{(int)currentBookEnum}");
            }
        }

        public enum BookEnum
        {
            Science = 100,
            Technology = 200,
            Engineering = 300,
            Mathematics = 400
        }
    }
}

 

posted @ 2024-05-20 20:03  FredGrit  阅读(7)  评论(0编辑  收藏  举报