문제
저는 오랫동안 C#을 사용해 왔지만 해시를 새로 만드는 쉬운 방법을 본 적이 없습니다.
나는 최근에 해시의 루비 구문에 대해 알게 되었는데, 모든 추가 호출을 수행하지 않고 해시를 리터럴로 선언하는 간단한 방법을 아는 사람이 있습니까?
{ "whatever" => {i => 1}; "and then something else" => {j => 2}};
해결책
C# 3.0(.NET 3.5)을 사용하는 경우 컬렉션 이니셜라이저를 사용할 수 있습니다.Ruby만큼 간결하지는 않지만 여전히 개선되었습니다.
이 예는 다음을 기반으로 합니다. MSDN 예
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, }}
};
다른 팁
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
);
C# 3.0(.NET 3.5)에서는 해시 테이블 리터럴을 다음과 같이 지정할 수 있습니다.
var ht = new Hashtable {
{ "whatever", new Hashtable {
{"i", 1}
} },
{ "and then something else", new Hashtable {
{"j", 2}
} }
};
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;
}
}
}
제휴하지 않습니다 StackOverflow