Linux 拨号vps windows公众号手机端

c#字典遍历使用的方法是什么

lewis 8年前 (2017-04-15) 阅读数 9 #程序编程
文章标签 c#

在C#中,遍历字典的方法有以下几种:

  1. 使用foreach循环遍历字典中的键值对:
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (KeyValuePair<string, int> kvp in dict)
{
    string key = kvp.Key;
    int value = kvp.Value;
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
  1. 使用foreach循环遍历字典中的键:
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (string key in dict.Keys)
{
    int value = dict[key];
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
  1. 使用foreach循环遍历字典中的值:
Dictionary<string, int> dict = new Dictionary<string, int>();

foreach (int value in dict.Values)
{
    Console.WriteLine("Value: {0}", value);
}
  1. 使用LINQ查询表达式遍历字典中的键值对:
Dictionary<string, int> dict = new Dictionary<string, int>();

var query = from kvp in dict
            select kvp;

foreach (var kvp in query)
{
    string key = kvp.Key;
    int value = kvp.Value;
    Console.WriteLine("Key: {0}, Value: {1}", key, value);
}
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门