开发者

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.

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. 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.


Nope. This is completely fine. .NET sequences are just nice like that. :D

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜