简体   繁体   中英

How do I Check and compare if a string is matched in a enum and return its position integer in a new variable C#

This is my enumeration:

enum Stations 
{
    Central, 
    RomaStreet, 
    Milton, 
    Auchenflower, 
    Toowong, 
    Taringa, 
    Indooroopilly 
};

this is my code:

static string DepartureStation(){
    string departStationinput;
    string departStation;

    if (departStation == null){
        Console.WriteLine("Please Enter one of  the names of the stations listed above! ");
        departStationinput = Console.ReadLine(); // Gets String 
        departStation = departStationinput.ToUpper(); // Converts String into UPPER CASE
        /*Need to check if the string is matched in the ENUM and return a variable/Value for it*/

    }
    return departStation;
}

You can use Enum.IsDefined method then parse the value:

if(Enum.IsDefined(typeof(Stations), departStationinput)
{
    var value = Enum.Parse(typeof(Stations), departStationinput);
}

Or you can use Enum.TryParse directly:

Stations enumValue;
if(Enum.TryParse(departStationinput, out enumValue))
{

}

If you want to ignore case sensitivity there is also another overload that you can use.

First of all, about integer position , it depends on what you expect as integer position :

  • It may be the enumeration integer value.
  • The index of the enumeration value.

If you want the integer value, it's about doing this:

int value = (int)Enum.Parse(typeof(Stations), "Central"); // Substitute "Central" with a string variable

In the other hand, since enumeration values may not be always 1, 2, 3, 4..., if you're looking for the index like an 1D array:

int index = Array.IndexOf
(
     Enum.GetValues(typeof(Stations))
            .Select(value => value.ToString("f"))
            .ToArray(),
     "Central"
);
var val = Enum.Parse(typeof(YourEnumType),name);

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