質問

私は長い間 C# を使ってきましたが、ハッシュを新しく作成するだけの簡単な方法に出会ったことがありません。

最近、ハッシュの Ruby 構文に慣れてきたのですが、add 呼び出しをすべて行わずにハッシュをリテラルとして宣言する簡単な方法を知っている人はいるでしょうか。

{ "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;            
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top