In the Dictionary collection, store any data type. A dictionary is a collection of keys and values in C#. Dictionary
Now let us see the best way to iterate over a dictionary in C# -
First, let us create the dictionary -
var d = new Dictionary<string, int>(5);
Now add the keys and values -
// add key and value d.Add("car", 25); d.Add("bus", 28); d.Add("motorbike", 17);
Use orderby to sort by value−
var val = from ele in d orderby ele.Value ascending select ele;
We set the ascending order above to sort the dictionary in ascending order. You can also use descending order.
Display values in ascending order -
foreach (KeyValuePair<string, int> ele in val) { Console.WriteLine("{0} = {1}", ele.Key, ele.Value); }
The above is the detailed content of What is the best way to iterate over a dictionary in C#?. For more information, please follow other related articles on the PHP Chinese website!