什么是从一个字典中的值和键复制到另一个在C#中最快的方法是什么? [英] What's the fastest way to copy the values and keys from one dictionary into another in C#?
问题描述
似乎没有成为一个dictionary.AddRange()方法。有谁知道一个更好的方式来复制项目到另一个词典不使用foreach循环。
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.
我使用的System.Collections.Generic.Dictionary。这是.NET 2.0。
I'm using the System.Collections.Generic.Dictionary. This is for .NET 2.0.
推荐答案
有没有错,一个用于/ foreach循环。这就是一个假设的AddRange方法,无论如何都会做的。
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.
这篇关于什么是从一个字典中的值和键复制到另一个在C#中最快的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!