如何在C#中向Dictionary添加多个值

Loc*_*rst 19 c# dictionary

如果我不想多次调用".Add()",那么向Dictionary添加多个值的最佳方法是什么? 编辑:我想在启动后填写它!字典中已有一些值!

而不是

    myDictionary.Add("a", "b");
    myDictionary.Add("f", "v");
    myDictionary.Add("s", "d");
    myDictionary.Add("r", "m");
    ...
Run Code Online (Sandbox Code Playgroud)

我想做这样的事情

 myDictionary.Add(["a","b"], ["f","v"],["s","d"]);
Run Code Online (Sandbox Code Playgroud)

有这样的方法吗?

Car*_*iel 19

您可以使用花括号,但这仅适用于初始化:

var myDictionary = new Dictionary<string, string>
{
    {"a", "b"},
    {"f", "v"},
    {"s", "d"},
    {"r", "m"}
};
Run Code Online (Sandbox Code Playgroud)

这就是所谓的"集合初始化",并适用于任何ICollection<T>(见链接的字典或该链接的任何其他集合型).实际上,它适用于实现IEnumerable和包含Add方法的任何对象类型:

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}
};
Run Code Online (Sandbox Code Playgroud)

基本上这只是Add反复调用-method的语法糖.初始化后有几种方法可以做到这一点,其中一种方法是Add手动调用-methods:

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);
}
Run Code Online (Sandbox Code Playgroud)

或者作为扩展方法:

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"}
    });
Run Code Online (Sandbox Code Playgroud)

  • 只是另一个for/foreach循环与`Add`组合.这只是添加方法的语法糖.对于`Dictionary <TKey,TValue>`,没有"AddRange"这样的东西,因为无论如何都需要对密钥进行哈希处理. (2认同)

cat*_*ood 6

这不是一个重复的问题,但你可能想要的是有一个Dictionary.AddRange()方法.这就是为什么不存在的原因:

为什么Dictionary没有AddRange?

"Range对于关联容器没有任何意义."

但是将自己的.AddRange()方法编写到Dictionary类可能是个好主意.它本质上是一个.Add()电话循环.

  • 他可能想要的是`.AddMultiple()`,或者`.AddMany()`,或者其他什么,即暗示整数索引的“范围”一词,不是他想要的。 (4认同)

Chr*_*air 5

尽管问题已经得到解答,但我很好奇是否可以将类似集合初始化程序的语法应用于已经初始化的字典,而无需创建/创建第二个字典以合并和丢弃的开销。

您可以使用(滥用?)集合初始值设定项在创建现有字典后将一系列值添加到该字典中。如何?通过创建一个辅助类来做到这一点:

public class AddRangeTo<TKey, TValue> : IEnumerable
{
    private readonly IDictionary<TKey, TValue> WrappedDictionary;

    public AddRangeTo(IDictionary<TKey, TValue> wrappedDictionary)
    {
        this.WrappedDictionary = wrappedDictionary;
    }

    public void Add(TKey key, TValue value)
    {
        this.WrappedDictionary.Add(key, value);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

与用法:

var myDictionary = new Dictionary<string, string>();

new AddRangeTo<string, string>(myDictionary)
{
    {"a", "b"},
    {"f", "v"},
    {"s", "d"},
    {"r", "m"}
};
Run Code Online (Sandbox Code Playgroud)

请注意,这允许您使用类似的语法将条目添加到字典中,但添加到已经初始化的字典中。有点糟糕的部分是<string, string>泛型的重复,但在 C# 6.0 中就没有必要了。(编辑:也就是说,在 C# 6 中它看起来像new AddRangeTo(myDictionary)(编辑:此功能已从 C# 6 中废弃)

话虽这么说,我真的不建议这样做。这是奇怪的语法/用法,具有意想不到的副作用,我认为其他人遇到它时可能会感到困惑。但如果您发现您实际上会经常使用它并使您的内部代码更易于使用和维护,那么奖金!