Search code examples
c#dictionarycopyforeach

What's the fastest way to copy the values and keys from one dictionary into another in C#?


There doesn't seem to be a dictionary.AddRange() method. Does anyone know a better way to copy the items to another dictionary without using a foreach loop.

I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0.


Solution

  • There's nothing wrong with a for/foreach loop. That's all a hypothetical AddRange method would do anyway.

    The only extra concern I'd have is with memory allocation behaviour, because adding a large number of entries could cause multiple reallocations and re-hashes. There's no way to increase the capacity of an existing Dictionary by a given amount. You might be better off allocating a new Dictionary with sufficient capacity for both current ones, but you'd still need a loop to load at least one of them.