【发布时间】:2020-01-29 10:51:27
【问题描述】:
我有一个字典 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返回一个新列表。修改它不会改变原来的。如果你想更新列表,你首先不应该使用IEnumerable,而应该使用ICollection。 -
myDictionary[key] = new IEnumerable based on old
标签: c# linq dictionary linq-to-entities