Home >Backend Development >C#.Net Tutorial >What is the best way to iterate over a dictionary in C#?

What is the best way to iterate over a dictionary in C#?

WBOY
WBOYforward
2023-09-13 16:49:06710browse

在 C# 中迭代​​字典的最佳方法是什么?

In the Dictionary collection, store any data type. A dictionary is a collection of keys and values ​​in C#. Dictionary is contained in the System.Collection.Generics namespace.

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete