2008-09-09 21 views
28

我一直在做C#很长一段时间,从来没有遇到过一个简单的方法来只是新的哈希。在C#中的文字哈希?

我最近熟悉了散列的ruby语法和奇迹,有没有人知道一个简单的方法来声明一个散列作为一个文字,没有做所有的添加调用。

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

回答

31

如果您使用的是C#3.0(.NET 3.5),那么您可以使用集合初始值设定项。它们不像Ruby那么简洁,但仍然有所改进。

这个例子是基于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

BTW:VisualStudio的/ ReSharper的告诉我,新的Dictionary ()中的圆括号是可选的和多余的。保存两个字符;) – 2009-06-10 15:59:33

7

当我不能使用C#3.0中,我用翻译一组参数到字典中的辅助功能。

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

使用这样的:

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

由于C#3.0(.NET 3.5)哈希表的文字可以像这样被指定:

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