【问题标题】:Add an Array to a Dictionary in C#在 C# 中将数组添加到字典中
【发布时间】:2012-03-20 13:30:00
【问题描述】:

我已尝试阅读有关此主题的其他帖子,但无法完全弄清楚。

我在 C# 中有一个列表,我想将它放入包含所有相同键的字典中。名单是这样的

string[] IN ={"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For"
    ,"Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"};

我想创建并填充一个字典,键为“IN”(数组的名称),然后将数组的每个字符串都放在字典中。

这是我为创建字典而写的(我不确定它是否正确):

Dictionary<string, List<string>> wordDictionary = new Dictionary<string, List<string>> ()

但我不确定如何填充字典。

任何帮助将不胜感激,因为这是我第一次尝试使用字典,而且我是 C# 新手

【问题讨论】:

  • 您实际上是要添加字符串数组“IN”还是要说要添加变量的名称?此外,这个要求似乎是一种糟糕的结构方式......我敢打赌,如果你解释你想要完成的事情,我们可以提供更好的解决方案。

标签: c# arrays dictionary


【解决方案1】:

数组是string[],而不是List&lt;string&gt;,所以这样做:

Dictionary<string, string[]> wordDictionary = new Dictionary<string, string[]>();

现在你可以像往常一样添加你的数组了。

wordDictionary.Add("IN", IN);

或者:

wordDictionary.Add("IN", new string[] {"Against","Like","Upon","Through","Of","With","Upon","On","Into","From","by","that","In","About","For","Along","Before","Beneath","At","Across","beside","After","Though","Among","Toward","If"});

【讨论】:

  • Minitech,非常感谢!我想我现在的问题是如何访问字典中数组中的各个字符串?
  • @miltonjbradley:和其他数组一样;通过索引(wordDictionary["IN"][0] == "Against")或以某种方式循环(foreach(string word in wordDictionary["IN"]))。
【解决方案2】:
Dictionary.Add("IN", new List<string>(IN));

...如果您想保留字典的当前签名。

如果您将其更改为Dictionary&lt;string, string[]&gt;,那么您可以:

Dictionary.Add("IN",IN);

【讨论】:

    【解决方案3】:

    你当前有一个字符串数组,而不是一个列表——所以它应该是:

    Dictionary<string, string[]> wordDictionary  = new Dictionary<string,string[]> ()
    

    然后您可以添加以下项目:

    wordDictionary.Add("IN" , IN);
    

    【讨论】:

      【解决方案4】:

      您真的需要将数组转换为字符串吗?您可以很好地在字典中使用 string[] 而不是 List:

      var wordDictionary = new Dictionary<string, string[]>();
      wordDictionary.Add("IN", IN);
      

      但是如果你真的想把你的字符串数组转换成 List:

      var wordDictionary = new Dictionary<string, List<string>>();
      wordDictionary.Add("IN", IN.ToList());
      

      【讨论】:

        【解决方案5】:

        将数组(不是列表)添加到字典的另一种方法是使用集合初始化器:

        var wordDictionary = new Dictionary<string, string[]> { "IN", IN };
        

        这与以正常方式创建字典然后调用Add("IN", IN)完全相同

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-29
          • 1970-01-01
          • 1970-01-01
          • 2014-05-21
          • 1970-01-01
          相关资源
          最近更新 更多