简体   繁体   English

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

[英]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.似乎没有 dictionary.AddRange() 方法。 Does anyone know a better way to copy the items to another dictionary without using a foreach loop.有谁知道在不使用 foreach 循环的情况下将项目复制到另一个字典的更好方法。

I'm using the System.Collections.Generic.Dictionary.我正在使用 System.Collections.Generic.Dictionary。 This is for .NET 2.0.这适用于 .NET 2.0。

There's the Dictionary constructor that takes another Dictionary .有一个Dictionary构造函数,它接受另一个Dictionary

You'll have to cast it IDictionary , but there is an Add() overload that takes KeyValuePair<TKey, TValue> .您必须将其转换为IDictionary ,但有一个Add()重载需要KeyValuePair<TKey, TValue> You're still using foreach, though.不过,您仍在使用 foreach。

There's nothing wrong with a for/foreach loop. for/foreach 循环没有任何问题。 That's all a hypothetical AddRange method would do anyway.无论如何,这就是一个假设的 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.您最好为两个当前字典分配一个具有足够容量的新字典,但您仍然需要一个循环来加载其中至少一个。

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

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

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

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<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;
        }

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();
    }
}

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 方法来吸收它们。

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 new Dictionary pointing to new objects, I think that the only way is through a foreach .如果你想创建一个指向对象的字典,我认为唯一的方法是通过foreach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM