繁体   English   中英

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

[英]How to add multiple values to Dictionary in C#

如果我不想多次调用“.Add()”,那么向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"]);

有这样的方法吗?

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

var myDictionary = new Dictionary<string, string>
{
    {"a", "b"},
    {"f", "v"},
    {"s", "d"},
    {"r", "m"}
};

这就是所谓的“集合初始化”,并适用于任何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}
};

基本上这只是反复调用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);
}

或者作为扩展方法:

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"}
    });

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

为什么Dictionary没有AddRange?

“Range对于关联容器没有任何意义。”

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

虽然问题已得到解答,但我很好奇是否有可能将类似集合初始化器的语法应用于已经初始化的字典,而没有创建/开销创建第二个字典以进行合并和丢弃。

您可以使用(滥用?) Collection Initializers 创建为现有Dictionary添加一系列值。 怎么样? 通过创建一个帮助程序类来执行它:

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();
    }
}

用法:

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

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

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

尽管如此,我并不是真的建议这样做。 这是奇怪的语法/用法与意想不到的副作用,我认为当他们遇到它时可能会让其他人感到困惑。 但是如果你发现你实际上会使用它并使你的内部代码更容易使用和维护,那么奖金!

你可以这样做:

var myDict = new Dictionary<string, string>() 
{
    {"a", "aa"},
    {"b", "bb"},
    {"c", "cc"},
    {"d", "dd"}
};

您可以在初始化时像所有其他答案节目一样进行,或者您可以将其与此技巧结合使用:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();
Dictionary<string, string> secondDictionary = new Dictionary<string, string>()
{ 
    {"1", "a"}, 
    {"2", b"} 
};
myDictionary = myDictionary.Union(secondDictionary)
                           .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

您必须确保没有重复的密钥或者您将获得异常(但这与Add方法相同)。

这将是一个简单的谷歌搜索: http//msdn.microsoft.com/en-us/library/bb531208.aspx 无论如何......这是代码:

Dictionary<string, string> myDictionary = new Dictionary<string, string>()
{
    { 'a', 'b' },
    { 'c', 'd' },
    { 'e', 'f' }
};

当然,您也可以编写一个循环或其他东西来迭代您的值并每次调用.add()方法。

好吧,你可以初始化:

new Dictionary<string, string> { {"a","b"}, {"f","v"},{"s","d"} }

这称为集合初始值设定项。 如果要将多个项目添加到现有字典中,可以编写方法。

这可以通过主代码路径完成,允许您使用扩展方法减少发生的混乱。

public static class DictionaryExtensions
{
  public static IDictionary<TKey,TValue> AddRange<TKey,TValue>(
               this IDictionary<TKey,TValue> source,
               params  KeyValuePair<TKey,TValue>[] items)
  {
    foreach (var keyValuePair in items)
    {
      source.Add(keyValuePair.Key, keyValuePair.Value);
    }
    return source;
  }
}

myDictionary = new Dictionary(){{“a”,2)},{“b”,3},};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM