How to get enum when i have just a short display n

2019-06-02 16:56发布

问题:

I get a Short Diplay name and i need to get enum value using it?

[Display(Name = "Alabama", ShortName = "AL")]
        Alabama = 1,

i just get AL from outside database. I need to read somehow my enum and get a proper value. Thanks for any help guys.

回答1:

You can use the Enum.Parse or Enum.TryParse methods of the Enum class.

Sample:

CountryCodeEnum value = (CountryCodeEnum)Enum.Parse(SomeEnumStringValue);


回答2:

If you are given the value AL, and you want to find the enum value that has that attribute, you can use a little bit of reflection to figure that out.

Let's say our enum looks like this:

public enum Foo
{
    [Display(Name = "Alabama", ShortName = "AL")]
    Alabama = 1,
}

Here is a little code to get the Foo which has an attribute of ShortName = 'AL':

var shortName = "AL"; //Or whatever
var fields = typeof (Foo).GetFields(BindingFlags.Static | BindingFlags.Public);
var values = from f
                in fields
            let attribute = Attribute.GetCustomAttribute(f, typeof (DisplayAttribute)) as DisplayAttribute
            where attribute != null && attribute.ShortName == shortName
            select f.GetValue(null);
    //Todo: Check that "values" is not empty (wasn't found)
    Foo value = (Foo)values.First();
    //value will be Foo.Alabama.


回答3:

Thanks to help from the answers already given and from some additional research, I'd like to share my solution to this as an extension method in hope that it may help others:

public static void GetValueByShortName<T>(this Enum e, string shortName, T defaultValue, out T returnValue)
{
    returnValue = defaultValue;

    var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public)
                 let attribute = Attribute.GetCustomAttribute(f, typeof(DisplayAttribute)) as DisplayAttribute
                 where attribute != null && attribute.ShortName == shortName
                 select (T)f.GetValue(null);

    if (values.Count() > 0)
    {
        returnValue = (T)(object)values.FirstOrDefault();
    }
}

You can use this extension as such:

var type = MyEnum.Invalid;
type.GetValueByShortName(shortNameToFind, type, out type);
return type;


回答4:

@jasel i modify your code a little bit. this fits just fine what i need.

    public static T GetValueByShortName<T>(this string shortName)
    {
        var values = from f in typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public)
                     let attribute = Attribute.GetCustomAttribute(f, typeof(DisplayAttribute)) as DisplayAttribute
                     where attribute != null && attribute.ShortName == shortName
                     select (T)f.GetValue(null);

        if (values.Count() > 0)
        {
            return (T)(object)values.FirstOrDefault();
        }

        return default(T);
    }