在C#中,遍历字典的方法有以下几种:
- 使用foreach循环遍历字典中的键值对:
Dictionarydict = new Dictionary (); foreach (KeyValuePair kvp in dict) { string key = kvp.Key; int value = https://www.yisu.com/ask/kvp.Value;"Key: {0}, Value: {1}", key, value); }
- 使用foreach循环遍历字典中的键:
Dictionarydict = new Dictionary (); foreach (string key in dict.Keys) { int value = https://www.yisu.com/ask/dict[key];"Key: {0}, Value: {1}", key, value); }
- 使用foreach循环遍历字典中的值:
Dictionarydict = new Dictionary (); foreach (int value in dict.Values) { Console.WriteLine("Value: {0}", value); }
- 使用LINQ查询表达式遍历字典中的键值对:
Dictionarydict = new Dictionary (); var query = from kvp in dict select kvp; foreach (var kvp in query) { string key = kvp.Key; int value = https://www.yisu.com/ask/kvp.Value;"Key: {0}, Value: {1}", key, value); }