2013-02-20 13 views
63

Come si converte il seguente valore in un elenco di stringhe?Convertire un enum in elenco <string>

[Flags] 
public enum DataSourceTypes 
{ 
    None = 0, 
    Grid = 1, 
    ExcelFile = 2, 
    ODBC = 4 
}; 

Non sono riuscito a trovare questa domanda esatta, questo Enum to List è il più vicino, ma io voglio specificamente metodo statico List<string>

risposta

110

Usa Enum s', GetNames. Esso restituisce un string[], in questo modo:

Enum.GetNames(typeof(DataSourceTypes)) 

Se si desidera creare un metodo che fa solo questo per un solo tipo di enum, e anche converte tale matrice a un List, è possibile scrivere qualcosa di simile:

public List<string> GetDataSourceTypes() 
{ 
    return Enum.GetNames(typeof(DataSourceTypes)).ToList(); 
} 
+4

Hai appena fatto questa domanda così potresti rispondere da solo? – juharr

+6

Hai il permesso di chiedere e rispondere alla tua stessa domanda. la mia preoccupazione sarebbe che questa è una domanda doppia in ogni caso –

+1

avrebbe dovuto essere Wiki! –

17

voglio aggiungere un'altra soluzione: nel mio caso, ho bisogno di utilizzare un gruppo di Enum in un menu a discesa voci di elenco tasto. Così si potrebbero avere spazio, vale a dire più utenti descrizioni amichevole necessaria:

public enum CancelReasonsEnum 
{ 
    [Description("In rush")] 
    InRush, 
    [Description("Need more coffee")] 
    NeedMoreCoffee, 
    [Description("Call me back in 5 minutes!")] 
    In5Minutes 
} 

In una classe di supporto (HelperMethods) ho creato il seguente metodo:

public static List<string> GetListOfDescription<T>() where T : struct 
    { 
     Type t = typeof(T); 
     return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList(); 
    } 

Quando si chiama questo helper si otterrà la lista delle descrizioni degli articoli.

List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>(); 

AGGIUNTA: In ogni caso, se si desidera implementare questo metodo è necessario: estensione GetDescription per enum. Questo è quello che uso.

public static string GetDescription(this Enum value) 
    { 
     Type type = value.GetType(); 
     string name = Enum.GetName(type, value); 
     if (name != null) 
     { 
      FieldInfo field = type.GetField(name); 
      if (field != null) 
      { 
       DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute; 
       if (attr != null) 
       { 
        return attr.Description; 
       } 
      } 
     } 
     return null; 
     /* how to use 
      MyEnum x = MyEnum.NeedMoreCoffee; 
      string description = x.GetDescription(); 
     */ 

    } 
+1

Molto utile! Grazie;) –

+0

Questo copre un altro aspetto di questa domanda semplice ma molto popolare, grazie. –