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.