【问题标题】:How to add multiple values to Dictionary in C#?如何在 C# 中向字典添加多个值?
【发布时间】:2014-06-27 06:34:35
【问题描述】:

如果我不想多次调用“.Add()”,向字典添加多个值的最佳方法是什么。

编辑:我要在启动后填写!字典中已经有一些值了!

所以不是

    myDictionary.Add("a", "b");
    myDictionary.Add("f", "v");
    myDictionary.Add("s", "d");
    myDictionary.Add("r", "m");
    ...

我想做这样的事情

 myDictionary.Add(["a","b"], ["f","v"],["s","d"]);

有办法吗?

【问题讨论】:

标签: c# dictionary


【解决方案1】:

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

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

这称为“集合初始化”,适用于任何ICollection&lt;T&gt;(请参阅link 用于字典或此link 用于任何其他集合类型)。事实上,它适用于任何实现了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-方法的语法糖。初始化后有几种方法可以做到这一点,其中一种是手动调用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"}
    });

【讨论】:

  • 启动后无法填写?
  • 只是另一个结合Add 的for/foreach 循环。这只是 add 方法的语法糖。 Dictionary&lt;TKey, TValue&gt; 不存在 AddRange 这样的东西,因为无论如何都需要对密钥进行哈希处理。
【解决方案2】:

你可以这样做:

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

      好吧,你可以在初始化时:

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

      这称为集合初始化程序。 当你想将多个项目添加到一个已经存在的字典中时,你可以编写一个方法。

      【讨论】:

        【解决方案5】:

        您可以像所有其他答案一样在初始化时执行此操作,也可以将其与此技巧结合使用:

        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 方法相同)。

        【讨论】:

        • Union 将导致另一个 IEnumerable&lt;T&gt; 不再是字典。这也可能包含重复的键,因为KeyValuePair&lt;T&gt; 没有实现基于键的相等/哈希码(比如它创建了一个字典)。
        • 添加了ToDictionary 和重复键的备注。
        【解决方案6】:

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

        Why doesn't Dictionary have AddRange?

        “范围对关联容器没有任何意义。”

        但是将您自己的.AddRange() 方法写入Dictionary 类可能是个好主意。不过,它本质上是.Add() 调用的循环。

        【讨论】:

        • 他可能想要的是.AddMultiple(),或.AddMany(),或其他任何东西,即暗示整数索引的“范围”一词,不是他想要的。
        【解决方案7】:

        这可以在主代码路径之外完成,这样您就可以使用扩展方法减少发生混乱的地方。

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

        【讨论】:

          【解决方案8】:

          虽然问题已经得到解答,但我很好奇是否可以将类似集合初始化程序的语法应用于已经初始化的字典创建第二个字典的创建/开销合并扔掉。

          您可以使用(滥用?)Collection Initializers 将一系列值添加到现有字典在创建之后。如何?通过创建一个帮助类来做到这一点:

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

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

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

          【讨论】:

            【解决方案9】:

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

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-04-22
              • 1970-01-01
              • 2021-11-06
              • 1970-01-01
              • 2017-11-24
              • 2012-07-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多