C# sort dictionary

C# dictionary do not have a method such as sort. Following code can sort a dictionary.

using System.Collections.Generic;
Dictionary<string, int> dscore = new Dictionary<string, int>();
dscore.Add("Mary",4);
dscore.Add("Richard",43);
dscore.Add("Brown",98);
dscore.Add("Smith",54);
List<KeyValuePair<string, int>> lscore = new List<KeyValuePair<string, int>>(dscore);
lscore.Sort(
delegate(KeyValuePair<string, int> firstPair,
KeyValuePair<string, int> nextPair)
{
return firstPair.Value.CompareTo(nextPair.Value);
}
);
for (int i = lscore.Count - 1; i > 0; i--)
{
KeyValuePair<string, int> item = lscore[i];
string k = item.Key;
int val = item.Value;
...
}


endmemo.com © 2024  | Terms of Use | Privacy | Home