web analytics

How To Copy A Dictionary in C#

Options

codeling 1595 - 6639
@2017-10-26 10:04:02

A Dictionary in C# has a copy constructor. Its syntax is:

Dictionary<TKey, TValue> Constructor (IDictionary<TKey, TValue>)

When you pass an existing Dictionary to its constructor, it is copied. This is an effective way to copy a Dictionary's data. When the original Dictionary is modified, the copy is not affected.

public Dictionary<string, Variable> VariableReferences = new Dictionary<string, Variable>();

//...other code

constraintTask.VariableReferences = new Dictionary<string, Variable>(this.VariableReferences);

@2017-10-26 10:06:24

You can manually copy all elements in your Dictionary. Internally, the Dictionary constructor that accepts IDictionary is implemented with foreach loop.

foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
    this.Add(pair.Key, pair.Value);
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com