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

   2025-02-05 4780
核心提示:在C#中,遍历字典的方法有以下几种:使用foreach循环遍历字典中的键值对:Dictionarystring, int dict = new Dictionarystring,

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

使用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);}
使用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);}
使用foreach循环遍历字典中的值:
Dictionary<string, int> dict = new Dictionary<string, int>();foreach (int value in dict.Values){    Console.WriteLine("Value: {0}", value);}
使用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);}

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言