Search for a string in Enum and return the Enum

后端 未结 12 2205
礼貌的吻别
礼貌的吻别 2020-11-28 19:13

I have an enumeration:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

and I have a s

12条回答
  •  [愿得一人]
    2020-11-28 19:52

    You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

    Like this, for example:

    public MyColours GetColours(string colour)
    {
        foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
            if (mc.ToString().Contains(colour)) {
                return mc;
            }
        }
        return MyColours.Red; // Default value
    }
    

    or:

    public MyColours GetColours(string colour)
    {
        return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
    }
    

    The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

提交回复
热议问题