简体   繁体   English

获取字典 <K,V> 来自ConcurrentDictionary <K,V> 在.NET 4.0中

[英]Getting Dictionary<K,V> from ConcurrentDictionary<K,V> in .NET 4.0

I'm parallelizing some back-end code and trying not to break interfaces. 我正在并行化一些后端代码,并尝试不破坏接口。 We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on. 我们有几种返回Dictionary的方法,在内部,我正在使用ConcurrentDictionary在其上执行Parallel操作。

What's the best way to return Dictionary from these? 从这些返回字典的最佳方法是什么?

This feels almost too simple: 这感觉太简单了:

return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

I feel like I'm missing something. 我觉得我想念什么。

Constructing the Dictionary<K,V> directly will be slightly more efficient than calling ToDictionary . 构建Dictionary<K,V>直接稍微比调用更有效ToDictionary The constructor will pre-allocate the target dictionary to the correct size and won't need to resize on-the-fly as it goes along. 构造函数将为目标字典预先分配正确的大小,并且在进行过程中无需即时调整大小。

return new Dictionary<K,V>(myConcurrentDictionary);

If your ConcurrentDictionary<K,V> uses a custom IEqualityComparer<K> then you'll probably want to pass that into the constructor too . 如果您的ConcurrentDictionary<K,V>使用自定义IEqualityComparer<K>那么您可能也希望将其传递给构造函数

Nope. 不。 This is completely fine. 这是完全可以的。 .NET sequences are just nice like that. .NET序列就很好。 :D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM