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

本文关键字:字典 添加 数组 | 更新日期: 2023-09-27 18:26:35

我试着阅读了关于这个主题的其他帖子,但我不太明白。

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

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

数组是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"});
Dictionary.Add("IN", new List<string>(IN));

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

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

Dictionary.Add("IN",IN);

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

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

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

wordDictionary.Add("IN" , IN);

您真的需要将数组转换为字符串吗?你可以很好地使用字符串[]代替字典中的列表:

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

但是,如果您真的想将字符串数组转换为List:

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

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

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

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