tags:

views:

504

answers:

4
Dictionary<string, string> optionDictionary = new Dictionary<string, string>();

optionDictionary = ....;

SortedDictionary<string, string> optionsSorted;

if(sorting)
{
   optionsSorted = new SortedDictionary<string, string>(optionDictionary );
   // Convert SortedDictionary into Dictionary
}

return optionDictionary ;
+6  A: 

You can pass in your optionsSorted dictionary as a parameter to an instance of a new Disctionary. IE:

var dictionary = new Dictionary<type1,type2>(optionsSorted);
BFree
That will create a Dictionary which is not sorted on the key (because Dictionary is not a SortedDictionary). As the OP created a SortedDictionary from an unsorted Dictionary, I don't think this will help.
Renze de Waal
Um... where did he state he wants a Dictionary that's sorted? He said he wants to convert a SortedDictionary to a Dictionary. How do you propose having a sorted Dictionary if you don't use a SortedDictionary???
BFree
@BFree: We will need his/her opinion about what he/she wants. If you look at the code snippet, you'll see that he/she creates a Dictionary, and then uses a construct similar to yours to convert it to a SortedDictionary (if sorting is true). See my answer to see what I think he/she means.
Renze de Waal
Well my answer was accepted so I guess I did understand what they wanted.
BFree
I expect that he/she doesn't realise that the Dictionary that was created by new Dictionary<type1,type2<(optionsSorted) does not guarantee that the keys that are returned are returned in a defined order.
Renze de Waal
+1  A: 

Try the following

var dictionary = optionsSorted.ToDictionary(x => x.Key, x=> x.Value);
JaredPar
+1  A: 

Just use the ToDictionary method.

Alex Fort
+2  A: 

It is not entirely clear to me what you are trying to accomplish. I am assuming that you have a function that returns a Dictionary and you want it to be a sorted dictionary when sorting is true.

If that is true, then you need a return type that can be a Dictionary or a SortedDictionary.

If you want a single function doing that, I would use IDictionay as return type of the method.

Renze de Waal