2012-03-26 8 views
1

私は短いDiplayの名前を取得し、それを使用してenum値を取得する必要がありますか?表示名が短くてもenumを取得するには?

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

私はちょうど外部のデータベースからALを取得します。私は何とか私のenumを読んで、適切な価値を得る必要があります。助けを借りてくれてありがとう。

答えて

0

EnumクラスのEnum.ParseまたはEnum.TryParseメソッドを使用できます。

サンプル:

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

「Enum.Parse」は、列挙の属性には何の注意も払っていません。あなたがアラバマの代わりに "AL"を与えた場合(OPの指示どおり)、それは解析されません。 – vcsjones

0

あなたが値ALを与えている、とあなたはその属性を持つ列挙型の値を検索する場合、あなたはそれを把握するために反射の少しを使用することができます。

私たちの列挙型は、次のようになりましょう。ここでは

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

は短縮名=「AL」の属性を持つFooを得るために少しのコードです:から支援する

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. 
0

感謝既に与えられた回答といくつかの追加の研究から、他の人に役立つことを望んで、私はこれを拡張メソッドとして共有したいと思います:

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(); 
    } 
} 

次のようなこの拡張機能を使用することができます。

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

@jasel私はあなたのコードを少し変更します。これはちょうど私が必要なものに合う。

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); 
    } 
関連する問題