If you list items in a SortedDictionary , the items will be returned in the sort order of the item keys. And if you list the keys in a SortedDictionary , the keys will also be returned in sorted order. And, perhaps somewhat surprisingly, if you list the SortedDictionary values โโby its values, the values โโwill be returned in the sort order of the keys, rather than the sort order of the values โโas you might expect.
Demonstration:
Note that in this demo, items added to SortedDictionary are not added in sorted order.
In addition, if you plan to list a dictionary by its values โโand there is the possibility of duplicating the values , consider having a reverse search function to return IEnumerable <T> . (Of course, for large dictionaries, searching for a key by its value can lead to poor performance.)
using System; using System.Collections.Generic; using System.Linq; class SortedDictionaryEnumerationDemo { static void Main() { var dict = new SortedDictionary<int, string>(); dict.Add(4, "Four"); dict.Add(5, "Five"); dict.Add(1, "One"); dict.Add(3, "Three"); dict.Add(2, "Two"); Console.WriteLine("== Enumerating Items =="); foreach (var item in dict) { Console.WriteLine("{0} => {1}", item.Key, item.Value); } Console.WriteLine("\n== Enumerating Keys =="); foreach (int key in dict.Keys) { Console.WriteLine("{0} => {1}", key, dict[key]); } Console.WriteLine("\n== Enumerating Values =="); foreach (string value in dict.Values) { Console.WriteLine("{0} => {1}", value, GetKeyFromValue(dict, value)); } } static int GetKeyFromValue(SortedDictionary<int, string> dict, string value) {
Expected Result:
== Enumerating Items == 1 => One 2 => Two 3 => Three 4 => Four 5 => Five == Enumerating Keys == 1 => One 2 => Two 3 => Three 4 => Four 5 => Five == Enumerating Values == One => 1 Two => 2 Three => 3 Four => 4 Five => 5
DavidRR
source share