2009-10-21 23 views
8

Cómo convertir Enum a clave, pares de valores. Lo he convertido en C# 3.0.Convertir entradas en clave, pares de valores

public enum Translation 
    { 
     English, 
     Russian, 
     French, 
     German 
    } 

    string[] trans = Enum.GetNames(typeof(Translation)); 

    var v = trans.Select((value, key) => 
    new { value, key }).ToDictionary(x => x.key + 1, x => x.value); 

En C# 1.0 Cuál es la manera de hacerlo?

Respuesta

5

En C# 1 ...

string[] names = Enum.GetNames(typeof(Translation)); 

Hashtable hashTable = new Hashtable(); 
for (int i = 0; i < names.Length; i++) 
{ 
    hashTable[i + 1] = names[i]; 
} 

¿Seguro de que realmente desea un mapa de índice a nombre de embargo? Si solo está usando índices enteros, ¿por qué no simplemente usa una matriz o un ArrayList?

+0

Gracias. Acabo de terminar la escuela. Aprendí C#. Seguiré tu consejo, señor. – user193276

+0

Si quiero mejorar mi diseño (estilo de codificación) ¿debo enviar mi trabajo y solicitar opinión o solo se permite q & a simple en este foro? – user193276

+0

Bueno, las preguntas y respuestas específicas son ideales, pero las preguntas relacionadas con * pequeñas * piezas de código en términos de diseño, claridad, etc. están bien. Simplemente no envíe miles de líneas de código en una pregunta :) También ayuda si sus ejemplos son cortos y completos, en lugar de solo ser parte de un gran proyecto. –

16

para C# 3.0 si tienen una enumeración de esta manera:

public enum Translation 
{ 
    English = 1, 
    Russian = 2, 
    French = 4, 
    German = 5 
} 

no utilizan este:

string[] trans = Enum.GetNames(typeof(Translation)); 

var v = trans.Select((value, key) => 
new { value, key }).ToDictionary(x => x.key + 1, x => x.value); 

porque se hace un lío su clave (que es un entero).

En su lugar, usar algo como esto:

var dict = new Dictionary<int, string>(); 
foreach (var name in Enum.GetNames(typeof(Translation))) 
{ 
    dict.Add((int)Enum.Parse(typeof(Translation), name), name); 
} 
+0

Tenga en cuenta que en el segundo ejemplo (y supongo que el primero también si no usó índices) no admite enumeraciones con valores int duplicados – Arch

+0

¡Muchas gracias! Esto es realmente lo que estaba buscando. No pude entender el uso del Dictionary <> datatype en el proyecto real. – Tchaps

-1
var enumType = typeof(Translation); 
var objList = enumValuesList.Select(v => 
{ 
    var i = (Translation)Enum.Parse(enumType, v); 
    return new 
    { 
     Id = (int)i, 
     Value = v 
    }; 
}); 
0

no he leído la pregunta con cuidado, por lo que mi código no funcionará en C# 1.0, ya que utiliza los genéricos. Mejor uso con> = C# 4.0 (> = VS2010)

Para hacer la vida más fácil, he creado este servicio de ayuda.

El uso del servicio es la siguiente:

// create an instance of the service (or resolve it using DI) 
var svc = new EnumHelperService(); 

// call the MapEnumToDictionary method (replace TestEnum1 with your enum) 
var result = svc.MapEnumToDictionary<TestEnum1>(); 

El código de servicio es el siguiente:

/// <summary> 
/// This service provides helper methods for enums. 
/// </summary> 
public interface IEnumHelperService 
{ 
    /// <summary> 
    /// Maps the enum to dictionary. 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <returns></returns> 
    Dictionary<int, string> MapEnumToDictionary<T>(); 
} 

/// <summary> 
/// This service provides helper methods for enums. 
/// </summary> 
/// <seealso cref="Panviva.Status.Probe.Lib.Services.IEnumHelperService" /> 
public class EnumHelperService : IEnumHelperService 
{ 
    /// <summary> 
    /// Initializes a new instance of the <see cref="EnumHelperService"/> class. 
    /// </summary> 
    public EnumHelperService() 
    { 

    } 

    /// <summary> 
    /// Maps the enum to dictionary. 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <returns></returns> 
    /// <exception cref="System.ArgumentException">T must be an enumerated type</exception> 
    public Dictionary<int, string> MapEnumToDictionary<T>() 
    { 
     // Ensure T is an enumerator 
     if (!typeof(T).IsEnum) 
     { 
      throw new ArgumentException("T must be an enumerator type."); 
     } 

     // Return Enumertator as a Dictionary 
     return Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(i => (int)Convert.ChangeType(i, i.GetType()), t => t.ToString()); 
    } 
} 
+0

Pregunta específicamente pregunta por las respuestas de C# 1.0, las tuyas hacen uso de las características de la versión 2.0 (genéricos) y 3.0 ('var'). –

+0

Mi mal, no vi eso. –

0

Préstamos de la respuesta por @jamie

Coloque esto en una estática clase de extensión, haga typeof(Translation).ToValueList<int>();

/// <summary> 
    /// If an enum MyEnum is { a = 3, b = 5, c = 12 } then 
    /// typeof(MyEnum).ToValueList<<int>>() will return [3, 5, 12] 
    /// </summary> 
    /// <typeparam name="T"></typeparam> 
    /// <param name="enumType"></param> 
    /// <returns>List of values defined for enum constants</returns> 
    public static List<T> ToValueList<T>(this Type enumType) 
    { 
     return Enum.GetNames(enumType) 
      .Select(x => (T)Enum.Parse(enumType, x)) 
      .ToList(); 
    } 
Cuestiones relacionadas