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 ;
views:
504answers:
4
+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
2009-03-05 18:05:55
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
2009-03-05 19:51:23
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
2009-03-05 20:02:28
@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
2009-03-06 06:38:55
Well my answer was accepted so I guess I did understand what they wanted.
BFree
2009-03-06 17:57:32
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
2009-03-07 06:59:56
+1
A:
Try the following
var dictionary = optionsSorted.ToDictionary(x => x.Key, x=> x.Value);
JaredPar
2009-03-05 18:07:13
+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
2009-03-05 18:49:11