The following code snippet sorts a C# Dictionary by keys and by values.
public void SortDictionary()
{
// Create a dictionary with string key and Int16 value pair
Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
AuthorList.Add("Mahesh Chand", 35);
AuthorList.Add("Mike Gold", 25);
AuthorList.Add("Praveen Kumar", 29);
AuthorList.Add("Raj Beniwal", 21);
AuthorList.Add("Dinesh Beniwal", 84);
// Sorted by Key
Console.WriteLine("Sorted by Key");
Console.WriteLine("=============");
foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Key))
{
Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}
Console.WriteLine("=============");
// Sorted by Value
Console.WriteLine("Sorted by Value");
Console.WriteLine("=============");
foreach (KeyValuePair<string, Int16> author in AuthorList.OrderBy(key => key.Value))
{
Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}
}
Mahesh ChandPosted Jul 1, 2012, 12:08 PM
I agree Sam. I am working on one class at a time and once have the SortDirectory sample ready, will update this article. We need these articles so we can point guys on the forums automatically.
Sam HobbsPosted Jun 30, 2012, 4:53 PM
I think it is worth mentioning that the SortedDictionary class sorts the keys automatically so it would be the most efficient for retrieving in the sorted order of the keys.