2008-09-09 15 views
28

He estado haciendo C# durante mucho tiempo, y nunca he encontrado una manera fácil de simplemente actualizar un hash.hash literales en C#?

Recientemente me he familiarizado con la sintaxis de hash de rubíes y pregunto, ¿alguien sabe de una manera simple de declarar un hash como un literal, sin hacer todas las llamadas de adición.

{ "whatever" => {i => 1}; "and then something else" => {j => 2}}; 

Respuesta

31

Si está utilizando C# 3.0 (.NET 3.5), puede utilizar los inicializadores de recopilación. No son tan escuetos como en Ruby, pero son una mejora.

Este ejemplo se basa en la MSDN Example

var students = new Dictionary<int, StudentName>() 
{ 
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}}, 
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }}, 
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }} 
}; 
+3

Por cierto: VisualStudio/ReSharper me dice , que los paréntesis en el nuevo Diccionario () son opcionales y redundantes. Guarda dos caracteres;) –

7

Cuando no estoy capaz de utilizar C# 3.0, utilizo una función auxiliar que traduce un conjunto de parámetros en un diccionario.

public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data) 
{ 
    Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length/2)); 
    if (data == null || data.Length == 0) return dict; 

    KeyType key = default(KeyType); 
    ValueType value = default(ValueType); 

    for (int i = 0; i < data.Length; i++) 
    { 
     if (i % 2 == 0) 
      key = (KeyType) data[i]; 
     else 
     { 
      value = (ValueType) data[i]; 
      dict.Add(key, value); 
     } 
    } 

    return dict; 
} 

uso como esto:

IDictionary<string,object> myDictionary = Dict<string,object>(
    "foo", 50, 
    "bar", 100 
); 
-1
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Dictionary 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Program p = new Program();     
      Dictionary<object, object > d = p.Dic<object, object>("Age",32,"Height",177,"wrest",36);//(un)comment 
      //Dictionary<object, object> d = p.Dic<object, object>();//(un)comment 

      foreach(object o in d) 
      { 
       Console.WriteLine(" {0}",o.ToString()); 
      } 
      Console.ReadLine();  
     } 

     public Dictionary<K, V> Dic<K, V>(params object[] data) 
     {    
      //if (data.Length == 0 || data == null || data.Length % 2 != 0) return null; 
      if (data.Length == 0 || data == null || data.Length % 2 != 0) return new Dictionary<K,V>(1){{ (K)new Object(), (V)new object()}}; 

      Dictionary<K, V> dc = new Dictionary<K, V>(data.Length/2); 
      int i = 0; 
      while (i < data.Length) 
      { 
       dc.Add((K)data[i], (V)data[++i]); 
       i++;  
      } 
      return dc;    
     } 
    } 
} 
1

Puesto que C# 3.0 (.NET 3.5) literales tabla hash se pueden especificar de este modo:

var ht = new Hashtable { 
    { "whatever", new Hashtable { 
      {"i", 1} 
    } }, 
    { "and then something else", new Hashtable { 
      {"j", 2} 
    } } 
};