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
Release: 2023-09-13 16:49:06
forward
674 people have browsed it

在 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);
Copy after login

Now add the keys and values ​​-

// add key and value
d.Add("car", 25);
d.Add("bus", 28);
d.Add("motorbike", 17);
Copy after login

Use orderby to sort by value−

var val = from ele in d
orderby ele.Value ascending
select ele;
Copy after login

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);
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template