Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Does anyone know a better way to copy the items to another dictionary without using a foreach loop.

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

like image 558
Helephant Avatar asked Sep 17 '08 09:09

Helephant


People also ask

How do I copy a dictionary from one dictionary to another?

The dict. copy() method returns a shallow copy of the dictionary. The dictionary can also be copied using the = operator, which points to the same object as the original. So if any change is made in the copied dictionary will also reflect in the original dictionary.

How do I copy a key value pair to another dictionary in Python?

By using dict. copy() method we can copies the key-value in a original dictionary to another new dictionary and it will return a shallow copy of the given dictionary and it also helps the user to copy each and every element from the original dictionary.

What are the ways to copy a dictionary d2 to d1?

Copy a dictionary with a for loop To copy a dictionary it is also possible to use a for loop: >>> d1 = {'a':1,'b':2} >>> d2 = {} >>> for key in d1: ... d2[key] = d1[key] ...


1 Answers

There's the Dictionary constructor that takes another 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.

like image 198
ageektrapped Avatar answered Oct 22 '22 03:10

ageektrapped