简体   繁体   中英

How do you get a specific item in an enumeration by a variable integer in c#?

I have this enumeration list

enum Month
{
    January = 1,
    February,
    March,
    April,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}

I am gathering an integer from the console named input with a value of 1-12. How do I make it print out the corresponding month? Eg:1 = January, 6=June.

Thank you for your time and help!

You can cast the int to your Enum

var m = (Month)1;

Console.WriteLine(m.ToString());

But bear in mind if the enum value isn't defined it will simply print the int.

Alternatively you can use

var m = Enum.GetName(typeof(Month), 1);

which will return null if it isn't defined

I invite you to read the documentation about enums

And here is the answer to your question:

var input = Console.ReadLine();
int enumIntValue = int.Parse(input); // You can also use TryParse (safer).
Month month = (Month) enumIntValue; // You can use Enum.IsDefined before to check if the int value is valid for the enum. 
Console.WriteLine(month); // print out the month.

Read also: TryParse , Enum.IsDefined

For information purposes, to see all of the textual values in an enum, you can get the values like so...

static void Main(string[] args)
{
    var enumValues = Enum.GetValues(typeof(Month));

    foreach (var enumValue in enumValues)
        Console.WriteLine(enumValue);
}

You can convert the integer value to the corresponding Enum via a cast, and then get its string representation:

var monthEnum = (Month)yourIntValue;
var strEnum = monthEnum.ToString();

Note that if yourIntValue isn't a valid enum value (eg 0, or 13), then the program will still run, but will output the integer value.

Also note that a better way to get a month's name would be to use the CultureInfo class :

// the current culture info, from your computer
var culture = CultureInfo.CurrentCulture; 

// you can also specify a known culture 
culture = CultureInfo.GetCultureInfo("en")
var monthName = culture.DateTimeFormat.GetMonthName(yourIntValue);
var input= Console.ReadLine();
Month month = 0;
if (Enum.TryParse(input, out month)) //Using try parse is safer
{
Console.WriteLine(month.ToString());
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM