如果我實例化一個新的Dictionary
我可以在許多價值觀傳遞:添加幾行的C#字典一次
Dictionary<string, string> data = new Dictionary<string, string>(){
{ "Key1", "Value1" },
{ "Key2", "Value2" },
{ "Key3", "Value3" },
{ "Key4", "Value4" },
{ "Key5", "Value5" },
}
不過,如果我已經有一個Dictionary
,當它在一個參數傳遞,例如,我需要調用Add
爲每個鍵 - 值對:
data.Add("Key1", "Value1");
data.Add("Key2", "Value2");
data.Add("Key3", "Value3");
data.Add("Key4", "Value4");
data.Add("Key5", "Value5");
我不知道是否有一個爲在同一時間加入在大量值以現有的詞典一個「的簡寫」方法 - 優選天然?如果是這樣,一個權威的「不」是受歡迎的。
沒有我想找的那麼幹淨,但是這些是我所知道的兩種選擇。
這一個允許一次傳遞多個值,但需要創建一個新的Dictionary
而不是更新現有的一個:
Dictionary<string, string> newData = new Dictionary<string, string>(data)
{
{ "Key6", "Value6"},
{ "Key7", "Value7"},
{ "Key8", "Value8"},
};
它也可以創建一個擴展方法,但仍對每行調用Add
:
public static void AddMany<Tkey, TValue>(this Dictionary<Tkey, TValue> dict, Dictionary<Tkey, TValue> toAdd)
{
foreach(KeyValuePair<Tkey, TValue> row in toAdd)
{
dict.Add(row.Key, row.Value);
}
}
您在第一個示例中顯示的語法實際上被編譯器修改爲調用Add多次,所以效果相同 –
@MatthewSteeples作爲初學者很好的瞭解C#dev –
相關:https://stackoverflow.com/問題/ 6050633 /爲什麼 - 犯規 - 字典有-的AddRange –