在 C# 中将值和键从一个字典复制到另一个字典的最快方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/81552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:19:37  来源:igfitidea点击:

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

提问by Helephant

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.

似乎没有 dictionary.AddRange() 方法。有谁知道在不使用 foreach 循环的情况下将项目复制到另一个字典的更好方法。

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

我正在使用 System.Collections.Generic.Dictionary。这适用于 .NET 2.0。

采纳答案by Mike Dimmick

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

for/foreach 循环没有任何问题。无论如何,这就是一个假设的 AddRange 方法。

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.

我唯一需要担心的是内存分配行为,因为添加大量条目可能会导致多次重新分配和重新散列。没有办法将现有字典的容量增加给定的数量。您最好为两个当前字典分配一个具有足够容量的新字典,但您仍然需要一个循环来加载其中至少一个。

回答by ageektrapped

There's the Dictionaryconstructor that takes another Dictionary.

有一个Dictionary构造函数需要另一个Dictionary.

You'll have to cast it IDictionary, but there is an Add()overload that takes KeyValuePair<TKey, TValue>. You're still using foreach, though.

您必须对其进行强制转换IDictionary,但是Add()需要使用KeyValuePair<TKey, TValue>. 不过,您仍在使用 foreach。

回答by Oli

If you're dealing with two existing objects, you might get some mileage with the CopyTo method: http://msdn.microsoft.com/en-us/library/cc645053.aspx

如果您正在处理两个现有对象,则使用 CopyTo 方法可能会有所帮助:http: //msdn.microsoft.com/en-us/library/cc645053.aspx

Use the Add method of the other collection (receiver) to absorb them.

使用其他集合(接收器)的 Add 方法来吸收它们。

回答by Martin Marconcini

I don't understand, why not using the Dictionary( Dictionary ) (as suggested by ageektrapped ).

我不明白,为什么不使用 Dictionary( Dictionary ) (根据 ageektrapped 的建议)。

Do you want to perform a Shallow Copy or a Deep Copy? (that is, both Dictionaries pointing to the same references or new copies of every object inside the new dictionary?)

您要执行浅复制还是深复制?(也就是说,两个字典都指向新字典中每个对象的相同引用或新副本?)

If you want to create a newDictionary pointing to newobjects, I think that the only way is through a foreach.

如果你想创建一个指向对象的字典,我认为唯一的方法是通过foreach

回答by BFree

For fun, I created this extension method to dictionary. This should do a deep copy wherever possible.

为了好玩,我为字典创建了这个扩展方法。这应该尽可能地进行深度复制。

public static Dictionary<TKey, TValue> DeepCopy<TKey,TValue>(this Dictionary&lt;TKey, TValue> dictionary)
        {
            Dictionary<TKey, TValue> d2 = new Dictionary<TKey, TValue>();

            bool keyIsCloneable = default(TKey) is ICloneable;
            bool valueIsCloneable = default(TValue) is ICloneable;

            foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
            {
                TKey key = default(TKey);
                TValue value = default(TValue);
                if (keyIsCloneable)
                {
                    key = (TKey)((ICloneable)(kvp.Key)).Clone();
                }

                else
                {
                    key = kvp.Key;
                }

                if (valueIsCloneable)
                {
                    value = (TValue)((ICloneable)(kvp.Value)).Clone();
                }

                else
                {
                    value = kvp.Value;
                }

                d2.Add(key, value);
            }

            return d2;
        }

回答by Mahendra Thorat

var Animal = new Dictionary<string, string>();

one can pass existing animal Dictionary to the constructor.

可以将现有的动物字典传递给构造函数。

Dictionary<string, string> NewAnimals = new Dictionary<string, string>(Animal);

回答by Marcello

For a primitive type dictionary:

对于原始类型字典:

public void runIntDictionary()
{
    Dictionary<int, int> myIntegerDict = new Dictionary<int, int>() { { 0, 0 }, { 1, 1 }, { 2, 2 } };
    Dictionary<int, int> cloneIntegerDict = new Dictionary<int, int>();
    cloneIntegerDict = myIntegerDict.Select(x => x.Key).ToList().ToDictionary<int, int>(x => x, y => myIntegerDict[y]);
}

or with an Object that implement ICloneable:

或使用实现 ICloneable 的对象:

public void runObjectDictionary()
{
    Dictionary<int, number> myDict = new Dictionary<int, number>() { { 3, new number(3) }, { 4, new number(4) }, { 5, new number(5) } };
    Dictionary<int, number> cloneDict = new Dictionary<int, number>();
    cloneDict = myDict.Select(x => x.Key).ToList().ToDictionary<int, number>(x => x, y => myDict[y].Clone());
}

public class number : ICloneable
{
    public number()
    {
    }
    public number(int newNumber)
    {
        nr = newnumber;
    }
    public int nr;

    public object Clone()
    {
        return new number() { nr = nr };
    }
    public override string ToString()
    {
        return nr.ToString();
    }
}