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 callingToDictionary. 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.If your
ConcurrentDictionary<K,V>uses a customIEqualityComparer<K>then you’ll probably want to pass that into the constructor too.