在字典内的列表中添加新元素

时间:2015-04-08 13:15:18

标签: c# list dictionary

在字典中,我想为给定的密钥添加一个数字列表。但我无法做到。

for(int i = 0 ; i < size ; i++){
   string input = Console.ReadLine();
   string[] inputList = input.Split(' ');
   count[Convert.ToInt32(inputList[0])]++;
   if(!map.ContainsKey(Convert.ToInt32(inputList[0]))){
     map.Add(Convert.ToInt32(inputList[0]),new List<string>());
     map_index.Add(Convert.ToInt32(inputList[0]),new List<int>());
   }
}

3 个答案:

答案 0 :(得分:3)

问题有点不清楚。我对您的问题的理解如下:您有一个字典,字典的值是一个列表,并且您在向该列表添加项目时遇到问题。既然你没有解释你的符号,我会使用更多的通用名称,只是为了让你知道必须做些什么:

Dictionary<int, List<string>> myDict = new Dictionary<int, List<string>>();
if (myDict.ContainsKey(myKey))
{
    myDict[myKey].Add(myVal);
}
else
{
    myDict[myKey] = new List<string> { myVal };
}

如果密钥不在字典中,则与列表一起创建条目,并使用新值初始化列表。如果密钥在那里,您只需访问列表(使用myDict[myKey])并将新值添加到列表中。由于列表始终是为新密钥创建的,因此在为现有密钥添加值时,不必担心它未初始化。

答案 1 :(得分:0)

这可能是一种有效的解决方案,并且比if-else容易得多。

Dictionary<int, List<string>> myDict = new Dictionary<int, List<string>>();
try
{
    myDict[myKey].Add(myVal);
}
catch
{
    myDict[myKey] = new List<string> { myVal };
}

答案 2 :(得分:0)

使用 AddOrUpdate 中的 ConcurrentDictionary 有一种“单命令行”方式:

using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
 
...

var dictionary = new ConcurrentDictionary<int, string[]>();
var itemToAdd = "item to add to key-list";

dictionary.AddOrUpdate(1, new[]{item1ToAdd}, (key, list) => list.Append(itemToAdd));

// If key 1 doesn't exist, creates it with a list containing itemToAdd as value
// If key 1 exists, adds item to already existent list (third parameter)