ToDictionary()上的MSDN文档没有说明它的实际工作原理。我想知道它是否创建了字典及其元素的副本,或者只是重用相同的引用和枚举器。
例如,如果我有一个ConcurrentDictionary c
,并且我通过调用d
创建了一个词典c.ToDictionary(...)
,我可以使用(想foreach
){{1}线程更新d
独立(以线程安全的方式)?
事实上,当我这样做时,我得到了:
收藏被修改;枚举操作可能无法执行。
...序列化c
时。
答案 0 :(得分:3)
Enumerable.ToDictionary
会为您的收藏集创建一个浅表副本。
true
正如您所看到的,它会创建一个新的public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
if (source == null) throw Error.ArgumentNull("source");
if (keySelector == null) throw Error.ArgumentNull("keySelector");
if (elementSelector == null) throw Error.ArgumentNull("elementSelector");
Dictionary<TKey, TElement> d = new Dictionary<TKey, TElement>(comparer);
foreach (TSource element in source) d.Add(keySelector(element), elementSelector(element));
return d;
}
,迭代您的集合并添加所有元素,应用选择器函数。因此,如果您更新原始集合,则字典不会更新,反之亦然。