2

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?

nawfal
  • 70,104
  • 56
  • 326
  • 368
Cyan
  • 1,068
  • 1
  • 12
  • 31
  • 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 Answers2

1

This stack overflow question includes a solution using LINQ.

How do you sort a dictionary by value?

Community
  • 1
  • 1
Mick N
  • 14,892
  • 2
  • 35
  • 41
  • i tried this code: Dictionary dict = new Dictionary(); 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? – Cyan Jan 30 '11 at 02:02
  • 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); 
nawfal
  • 70,104
  • 56
  • 326
  • 368
Cyan
  • 1,068
  • 1
  • 12
  • 31
  • 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