tags:

views:

180

answers:

5

Hello, I think there is a shorter way of writing this foreach loop that creates a deep copy of a SortedDictionary<string, object>. Note that object is just a place holder, I'm really using some other reference type there. Thanks!

Here is the code:

foreach (KeyValuePair<string, object> entry in sortedDictionary)
{
    this.mSortedDictionary.Add(entry.Key, new object());
}
+4  A: 

Whats the point, this is perfectly short.

And for the record, you can make an extension method for Dictioary (or IDictioary) that does this. From then on, you can call the extension method on any dictioary.

Henri
+3  A: 
mSortedDictionary = sortedDictionary.ToDictionary(kvp => kvp.Key, kvp => new Object());
STO
...this is not equivalent, the original code may be adding the items to an existing dictionary...
Lucero
Please no.. lambdas just make someone else's job harder when they have to read your code two months down the line ;-)
PjL
A: 
foreach( string key in sortedDictionary.Keys ) {
   mSortedDictionary.Add(key, new object());
}
PjL
The OP stated that the `new object()` line was just a placeholder, presumably for deep-copy of the object referenced by the original dictionary. Enumerating over keys does not solve the problem.
drharris
Of course it does, e.g.: mSortedDictionary.Add(key, sortedDictionary[key].Clone());.. but "presumably" indicates your interpretation of the question.
PjL
+1  A: 

Grab the nVentive Umbrella Extensions library (http://umbrella.codeplex.com) and:

sortedDictionary.ForEach(s => mSortedDictionary.Add(s, new object()));
David
+2  A: 
Jörg W Mittag
wow... I've got a lot to learn.
kirk.burleson
that is awesome. : D
Robert Karl