在C#中将数组添加到字典

时间:2012-03-02 01:05:34

标签: c# arrays dictionary

我曾尝试阅读有关此主题的其他帖子,但无法弄清楚这一点。

我在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#的新手

5 个答案:

答案 0 :(得分:12)

数组是string[],而不是List<string>,所以只需执行此操作:

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

答案 1 :(得分:1)

您目前有一个字符串 array ,而不是列表 - 所以应该是:

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

然后你可以添加如下项目:

wordDictionary.Add("IN" , IN);

答案 2 :(得分:1)

Dictionary.Add("IN", new List<string>(IN));

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

如果您将其更改为Dictionary<string, string[]>,那么您可以:

Dictionary.Add("IN",IN);

答案 3 :(得分:0)

您真的需要将数组转换为字符串吗?您可以在字典中使用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());

答案 4 :(得分:0)

将数组(它不是列表)添加到字典的另一种方法是使用集合初始值设定项:

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

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