如何遍历字典并将项目添加到其值中

How to iterate over a dictionary and add items to its values

我有一个字典 Dictionary>,我迭代了它的键,并想将更多项目的集合添加到 SomeKindOfObject价值。 AddRange 不起作用 - 它不会更改该条目的值。 查看我的代码(或多或少):

Dictionary<int, IEnumerable<SomeObject>> myDictionary = setDictionary(); //Assume that this method populate the dictionary.
IEnumerable<int> keys = myDictionary.Keys;
foreach (int key in keys)
{
  myDictionary[key].ToList().AddRange(getListOfSomeObject()); // getListOfSomeObject returns IEnumerable<SomeObject>  
  //Or even
  myDictionary[key].ToList().concat(getListOfSomeObject()); 

}

myDictionary 值保持原样,我想使用 AddRange 方法而不是使用原始值和 getListOfSomeObject 方法的输出的组合列表设置值

ToList() 将创建一个新列表。如果修改它,存储在Dictionary 中的列表不会改变。再次将新创建的列表分配给 Dictionary.

Dictionary<int, IEnumerable<SomeObject>> myDictionary = setDictionary(); //Assume that this method populate the dictionary.
IEnumerable<int> keys = myDictionary.Keys;
foreach (int key in keys)
{
  var templist = myDictionary[key].ToList();
  templist.AddRange(getListOfSomeObject());
  myDictionary[key] = templist;

}

你能把你的词典类型改成Dictionary<int,List<SomeObject>>吗?然后就可以直接修改了。