2008-09-09 4 views
28

저는 오랫동안 C#을 해왔고 해시를 새로 시작하는 쉬운 방법을 처음 접한 적이 없습니다.C#에서 리터럴 해시?

나는 최근에 해시의 루비 구문에 대해 잘 알고 있으며, 모든 추가 호출을 수행하지 않고도 해시를 리터럴로 선언하는 간단한 방법을 알고있는 사람이 누구인지 알고 있습니다.

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

답변

31

C# 3.0 (.NET 3.5)을 사용하는 경우 컬렉션 초기화 프로그램을 사용할 수 있습니다. 루비만큼이나 간결하지만 아직 개선되지 않았습니다. 나는 C# 3.0을 사용할 수 아니에요 때

이 예

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

는 :으로 VisualStudio/ReSharper에서 저를 알려줍니다 new Dictionary ()의 괄호는 선택적이며 중복됨을 나타냅니다. 두 문자 저장;) –

7

을 기반으로, 나는 사전에 파라미터 세트를 변환하는 도우미 함수를 사용합니다. 이 같은

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) 해시 테이블 리터럴과 같이 지정 될 수 있기 때문에 : BTW

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