I need to sort a dictionary by it's key, since WP7 does not support SortedDictionary
. How can I do it nice, easy and optimal?
Asked
Active
Viewed 1,351 times
2
-
possible duplicate of [Sorting a Dictionary in place with respect to keys](http://stackoverflow.com/questions/2705607/sorting-a-dictionary-in-place-with-respect-to-keys) – nawfal Nov 05 '13 at 07:01
2 Answers
1
This stack overflow question includes a solution using LINQ.
-
i tried this code: Dictionary
dict = new Dictionary – Cyan Jan 30 '11 at 02:02(); dict.Add("3", "three"); dict.Add("1", "one"); dict.Add("2", "two"); var sortedDict = (from entry in dict orderby entry.Key ascending select entry); This works, but sortedDict is not a dictionary. how can I make it a dictionary? also, i tried dict.OrderBy(x => x.Key); this does not work. why? -
solved it: dict = (from entry in dict orderby entry.Key ascending select entry).ToDictionary(x=>x.Key, x=>x.Value); – Cyan Jan 30 '11 at 02:10
0
i tried this code:
Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("3", "three");
dict.Add("1", "one");
dict.Add("2", "two");
var sortedDict = (from entry in dict orderby entry.Key ascending select entry);
foreach (var k in sortedDict)
{
Console.WriteLine("key:{0}, val={1} ", k.Key, k.Value);
}
This works, but sortedDict is not a dictionary. I solved it:
sortedDict = (from entry in dict orderby entry.Key ascending select entry)
.ToDictionary(x => x.Key, x => x.Value);
-
solved it: dict = (from entry in dict orderby entry.Key ascending select entry).ToDictionary(x=>x.Key, x=>x.Value); – Cyan Jan 30 '11 at 02:11