如何在C#中向字典添加多个值 [英] How to add multiple values to Dictionary in C#
问题描述
如果我不想多次调用 .Add(),向字典添加多个值的最佳方法是什么。
编辑:我想在启动后填写它!
What is the best way to add multiple values to a Dictionary, if i dont want to call ".Add()" multiple times. Edit: I want to fill it after initiation! there are already some values in the Dictionary!
因此,而不是
myDictionary.Add("a", "b");
myDictionary.Add("f", "v");
myDictionary.Add("s", "d");
myDictionary.Add("r", "m");
...
我想做这样的事情
myDictionary.Add(["a","b"], ["f","v"],["s","d"]);
有办法吗?
推荐答案
您可以为此使用花括号,尽管这仅适用于初始化:
You can use curly braces for that, though this only works for initialization:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"},
{"s", "d"},
{"r", "m"}
};
这称为集合初始化,适用于任何 ICollection< T>
(请参阅链接了解字典或此< a href = http://msdn.microsoft.com/zh-cn/library/bb384062.aspx rel = noreferrer>链接(对于其他任何收集类型))。实际上,它适用于实现 IEnumerable
并包含 Add
方法的任何对象类型:
This is called "collection initialization" and works for any ICollection<T>
(see link for dictionaries or this link for any other collection type). In fact, it works for any object type that implements IEnumerable
and contains an Add
method:
class Foo : IEnumerable
{
public void Add<T1, T2, T3>(T1 t1, T2 t2, T3 t3) { }
// ...
}
Foo foo = new Foo
{
{1, 2, 3},
{2, 3, 4}
};
基本上,这只是调用 Add $ c $的语法糖c>-方法反复。初始化后,有几种方法可以执行此操作,其中一种是手动调用
Add
方法:
Basically this is just syntactic sugar for calling the Add
-method repeatedly. After initialization there are a few ways to do this, one of them being calling the Add
-methods manually:
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
var anotherDictionary = new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
};
// Merge anotherDictionary into myDictionary, which may throw
// (as usually) on duplicate keys
foreach (var keyValuePair in anotherDictionary)
{
myDictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
或作为扩展方法:
static class DictionaryExtensions
{
public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> target, IDictionary<TKey, TValue> source)
{
if (source == null) throw new ArgumentNullException("source");
if (target == null) throw new ArgumentNullException("target");
foreach (var keyValuePair in source)
{
target.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
var myDictionary = new Dictionary<string, string>
{
{"a", "b"},
{"f", "v"}
};
myDictionary.Add(new Dictionary<string, string>
{
{"s", "d"},
{"r", "m"}
});
这篇关于如何在C#中向字典添加多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!