Nicolas Webb
Nicolas Webb

Reputation: 1322

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.

Upvotes: 1

Views: 209

Answers (2)

LukeH
LukeH

Reputation: 269388

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.

Upvotes: 4

Squirrelsama
Squirrelsama

Reputation: 5570

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

Upvotes: 1

Related Questions