views:

13

answers:

2

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.

+1  A: 

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

Legatou
+2  A: 

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.

LukeH
Oh, I didn't know that. Good info!
Legatou