web analytics
How To Copy A Dictionary in C# Options
codeling
Posted: Thursday, October 26, 2017 10:04:02 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

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

Sponsor
Posted: Thursday, October 26, 2017 10:04:02 AM
 
codeling
Posted: Thursday, October 26, 2017 10:06:24 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 919
Points: 3861

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

Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.